Line by Line reading in Java using BufferedReader and Scanner
There are multiple ways to read file line by line in Java. Most simple example of reading file line by line is using BufferedReader which provides method readLine() for reading file. Apart from generics, enum and varargs Java 1.5 has also introduced several new class in Java API one of the utility class is Scanner, which can also be used to read any file line by line in Java. Though BufferedReader is available in Java from JDK 1.1, java.util.Scanner provides more utility methods compared to BufferedReader. Scanner has method like hasNextLine() and nextLine() to facilitate line by line reading of file's contents. nextLine() returns String similar to readLine() but scanner has more utility methods like nextInt(), nextLong() which can be used to directly read numbers from file instead of converting String to Integer or other Number classes. By the way Scanner is rather new approach for reading file and BufferedReader is the standard one. This is my 6th tutorial on Java IO, In last couple of post we have seen creating file and directory in Java, parsing XML files using DOM and how to read properties file in Java. In this post we will focus on reading file line by line in Java using both BufferedReader and Scanner.