How to read file line by line in Java
There are following ways to read a file line by line.
Using BufferedReader Class
Using the Java BufferedRedaer class is the most common and simple way to read a file line by line in Java. It belongs to java.io package. Java BufferedReader class provides readLine() method to read a file line by line. The signature of the method is:
The method reads a line of text. It returns a string containing the contents of the line. The line must be terminated by any one of a line feed ("\n") or carriage return ("\r").
Example of read a file line by line using BufferedReader class
In the following example, Demo.txt is read by FileReader class. The readLine() method of BufferedReader class reads file line by line, and each line appended to StringBuffer, followed by a linefeed. The content of the StringBuffer are then output to the console.
Using the Scanner class
Java Scanner class provides more utility methods compare to BufferedReader class. Java Scanner class provides the nextLine() method to facilitates line by line of file's content. The nextLine() methods returns the same String as readLine() method. The Scanner class can also read a file form InputStream.
Example of read a file line by line using Scanner class
Next TopicJava Tutorial
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week