How to read a file line by line in Java? BufferedReader Example

Hello Java Programmers, if you are looking for a way to read a file line by line in Java then don't worry, Java provides java.io  package in JDK API for reading File in Java from File system e.g. C:\ or D:\ drive in Windows or any other directory in UNIX. First, you can use FileInputStream to open a file for reading. FileInputStream takes a String parameter which is a path for the file you want to read. Be careful while specifying File path as path separator is different on Window and UNIX. Windows uses backslash while UNIX uses forward slash as a path separator. 

By the way, Java supports forward slash in Windows, It means if use forward slash your program will work on both Windows and UNIX. Alternatively, you can also get a PATH separator from System property path.separator. In this Java tutorial, we will code an example of  How to read Files line by line using BufferedReader in Java.


How to read a text file line by line in Java

How to read text file in Java with ExampleIn this Java sample, we will read a text file from C:\  drive in Windows machine but since Java is platform-independent and we have used PATH separator as a forward slash, it should work on any other UNIX based system e.g. Linux, Solaris, or IBM AIX. This is the most simple and standard way of reading the file in Java. 

Though you can read whole file byte by byte using FileInputStream,  or you can directly read String from InputStream in Java, we have used BufferedReader to read file line by line for better performance.





Java Program to read a text file line by line - Example


/**
 *
 * Java program to demonstrate how to read text files in Java.
 * Java API provides FileInputStream to open file for reading.
 * for improved performance it's advised that use Reader for reading contents
 * By using InputStreamReader you can convert an InputStream into Reader.
 * BufferedReader provides better performance while reading files in Java.
 * @author jdk67.blogspot.com
 */

public class FileReaderExample {

    public static void main(String args[]) {
        try {
            //opening file for reading in Java
            FileInputStream file
                = new FileInputStream("C:/test.txt");
            BufferedReader reader
                = new BufferedReader(new InputStreamReader(file));
         
            //reading file content line by line
            String line = reader.readLine();
            while(line != null){
                System.out.println(line);
                line = reader.readLine();
            }
                 
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CollectionTest.class.getName())
                   .log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CollectionTest.class.getName())
                   .log(Level.SEVERE, null, ex);
        }
    }
}

Output:
Java programming language has excellent support for File IO.
Java API provides several ways to read files from FileSystem.
From Java 7 onwards a new File API has been introduced which provides more features and improved performance.

If you look at this program, we have first opened FileInputStream pointing to file ("C:/test.txt") and then later read it.That's all on How to read Files in Java.

Related Java Tutorials
Difference between TreeSet and HashSet in Java


7 comments:

  1. Java7:
    new String(Files.readAllBytes(Paths.get("C:\test.txt")))

    ReplyDelete
  2. i got error to create class CollectionTest.class

    how to resolve it??

    ReplyDelete
    Replies
    1. Hello Prem, can you please explain bit more, what you are trying to do and when you get the error? May be just paste the error message here.

      Delete
  3. how to read file directly from the server???

    ReplyDelete
    Replies
    1. what do you mean by server? If you want to download the file from server, you can use HTTP or Socket connection or just stream using Socket.

      Delete
  4. how to compare the virus hash file with the drives files of the system in the java program for an antivirus?

    ReplyDelete
    Replies
    1. Can you provide more detail? If they are string then you can use equals() method, if they are integer, just use == operator

      Delete

Feel free to comment, ask questions if you have any doubt.