Thursday, February 16, 2023

2 Ways to Read a Text File in Java? BufferredReader and Scanner Examples

You can read a text file in Java by using either Files, BufferedReader or Scanner class. Both classes provide convenient methods to read a text file line by line e.g. Scanner provides nextLine() method and BufferedReader provides readLine() method. If you are reading a binary file, you can use FileInputStream. By the way, when you are reading text data, you also need to provide character encoding, if you don't then the platform's default character encoding is used. In Java IO, streams like InputStream are used to read bytes, and Readers like FileReader are used to read character data.

BufferedReader is the traditional way to read data because it reads file buffer by buffer instead of character by character, so it's more efficient if you are reading large files. BufferedReader is also there from JDK 1 itself while Scanner was added to Java 5.

The Scanner has more features than BufferedReader, when it comes to file reading, for example, you can specify any delimiter instead of the new line, which is not possible with BufferedReader. Java 7 added a new File API, which makes reading/writing from the file even easier.

It's also possible to read the entire file in one line in Java 7, but given most of the projects are still running on Java 6, it's good to know about these two ways to read a text file in Java. For Java beginners, I also suggest referring to a good book like Cay S. Horstmann, Core Java Volume 1 and 2 to learn the basics of Java programming.




How to read a text file in Java? Examples

You can read a text file in the Java program by using BufferedReader and Scanner and we will discuss steps to read a file in this article. First, we will see how to use the Scanner class to read a file line by line in Java, and then we will learn how to use BufferedReader class to do the same.


Example 1 - Reading File using Scanner in Java

Scanner class is defined in java.util package, so the first step is to import this class into your Java program. Once you imported this class, you can create an object of Scanner by passing a FileInputStream to it, pointing to the file you want to read. 

Now you are all set to read a text file line by line in Java. The scanner provides a method called hasNextLine() which returns true if the file has one more line to read.

This check is platform-independent so it will work in both Windows and UNIX even though the line separator is different in these two operating systems e.g. line separator is \n in Windows and \r\n in UNIX. 

You can read data from the file by calling nextLine() method, this will return the next line and advance the file pointer to the next line. This method returns a String object representing a line in the file. You can use a while() loop as shown in our first example, to read all lines from files one by one.

You can also see Core Java Volume 2 - Advanced Features by Cay S. Horstmann to learn more about how to use Scanner to read a file in Java.


Example 2 - Reading Text File using BufferedReader in Java

BufferedReader provides another way to read files line by line in Java. It follows a decorator pattern and adds buffering capability to an existing reader. You can create an object of InputStreamReader by passing FileInputStream, pointing to the text file you want to read. 

Optionally, you can also provide character encoding to the InputStreamReader, if you don't then it will use the platform's default character encoding. InputStreamReader actually acts as a bridge between streams and reader classes.

Once you have an object of BufferedReader, you can call the readLine() method to read the next line from the file. This method returns a String object containing data from a file, if there is no more line to read then this method return null. By using this properly, you can write a while loop to read a file line by line in Java, as shown in our second example.

Though I have not closed the buffered reader here, you should do it on your real production code, as suggested earlier on the right way to close streams in Java. It's better to call the close() method on the finally block. If you are on Java 7, consider using try-with-resource statement to automatically close resources once you are done with it. You can also use the Files class to read whole file in one line.

How to read text file in Java using BufferedReader and Scanner




Java Program to read a file line by line in Java

Here is our complete Java program to read a file in Java. This program contains two examples, the first example shows how to read a text file using the Scanner class and the second example shows how to read a file using BufferedReader class. 

Both classes are defined in java.util package so you need to import them before using them. If you are coding in Eclipse then don't worry, Eclipse will take care of it. In order to run this program from the command line,  create a  Java source file with the name FileReaderDemo.java and write this program there. 

Once you are done with it, you can follow the steps given on how to run Helloworld in Java to run this program from the command line. If you are using Eclipse IDE, then just select a Java project and copy-paste this code there, Eclipse will take care rest of it. To run a program in Eclipse, just right-click and select "Run as Java Program".


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * Java program to read File in Java. It demonstrate two ways by simple example,
 * one uses java.util.Scanner class and other by using java.io.BufferedReader
 * class.
 *
 * @author http://java67.blogspot.com
 *
 */

public class FileReaderDemo{

    public static void main(String args[]) throws IOException {

        final String FILE_NAME = "C://temp//GDP.txt";

        // 1st way to read File in Java - Using Scanner
        Scanner scnr = new Scanner(new FileInputStream(FILE_NAME));
        while (scnr.hasNextLine()) {
            System.out.println(scnr.nextLine());
        }
        scnr.close();

        // 2nd way to read File in Java - Using BufferedReader
        BufferedReader buffReader = new BufferedReader(
             new InputStreamReader(new FileInputStream(FILE_NAME)));
        String line = buffReader.readLine();
        while (line != null) {
            System.out.println(line);
            line = buffReader.readLine();
        }
    }
}

Output:

United States   18,390.900
China           15,923.626
India           5,750.467      
Japan           5,021.990      
Germany         3,440.437      
Russia          2,827.978      
Brazil          2,656.858      
United Kingdom  2,562.320      
France          2,416.128    
Mexico          2,040.222


That's all about how to read a text file in Java using BufferedReader and Scanner. Use Scanner if you are running on Java 5 or Java 6, or use BufferedReader if you are running on Java 1.4. You can use the Files class to read text files from Java 7 onward. 

If you like this tutorial and interested to learn more about Files and directories in Java, You can also take a look at the following Java tutorials :
  • How to read XLS and XLSX files in Java using Apache POI? (example)
  • How to create a file and directory in Java? (solution)
  • How to read XML files in Java using JDOM Parser? (solution)
  • How do you use the Scanner class in Java? (example)
  • How to use BufferedReader class in Java? (demo)
  • How do I read InputStream as String in Java? (solution)
  • How to read JSON Files in Java? (solution)
  • How do I read input from the console in Java? (example)
Don't forget to close the Scanner and BufferedReader object once you are done with it. Also, provide a character encoding if your file's encoding is different than the platform's character encoding.

1 comment:

  1. >>This check if platform independent so it will work in both Windows and UNIX even though line separator is different in these two operating system e.g. line separator is \n in Windows and \r\n in UNIX.<<

    This statement is wrong: As a line separator Windows is using \r\n and UNIX is using just \n

    ReplyDelete

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