Sunday 24 July 2016

How to read a text file using Scanner in Java? Example Tutorial

As I told you before that there are multiple ways to read a file in Java e.g. FileReader, BufferedReader, and FileInputStream. You chose the Reader or InputStream depending upon whether you are reading text data or binary data, for example, the BufferedReader class is mostly used to read a text file in Java. The Scanner class is also another way to read a text file in java. Even though Scanner is more popular as a utility to read user input from the command prompt, you will be glad to know that you can also read a file using Scanner. Similar to BufferedReader, it provides buffering but with a smaller buffer size of 1KB and you can also use the Scanner to read a file line by line in Java. Similar to readLine(), Scanner class also have nextLine() method which return the next line of the file. Scanner also provides parsing functionality e.g. you can not only read text but parse it into correct data type e.g. nextInt() can read integer and nextFloat() can read float and so on.
Read more »

No comments:

Post a Comment