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.
Reading file line by line in Java - BufferedReader Example
In this example we are using BufferedReader for reading file content line by line. BufferedReader needs an InputStream which is a FileInputStream in this case and readLine() returns value of line or null if end of Stream has reached. line is terminated with line terminator e.g. \n or \r
while using FileInputStream or any IO Reader don't forget to close the stream in finally block so that file descriptor associated with this operation get released. If not closed properly Java program may leak file descriptors which is a limited resource and in worst case program will not be able to open any new file. If you are Java 7 then you can use Automatic resource management or ARM blocks to let those resource automatically get closed by Java.
Reading file line by line in Java - Scanner Example
Scanner is new addition in Java 1.5 along-with several other changes like auto-boxing and has been a preferred choice for reading inputs from console. Since Scanner is able to read from InputStream , it can also be used to read from text File and it provide many utility methods to read line by line contents using nextLine() or nextInt() etc.
That's all on How to read file line by line in Java. We have seen two simple examples of line by line reading using BufferedReader and Scanner. If you look code with Scanner looks more clean and give wide variety of data conversion method it supports, it just an handy choice for reading file line by line in Java.
Other Java IO tutorials from Javarevisited blog