Wednesday, April 22, 2020

2 Ways to Read a Text File in Java - Examples

Oracle Java Tutorial and Materials, Oracle Java Prep, Oracle Java Guides

You can read a text file in Java 6 by using 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 use FileInputStream. By the way, when you are reading text data, you also need to provide character encoding, if you don't then 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.

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

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

How to read a text file in Java?


You an read a text file in 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 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.

Solution 1 - Reading File using Scanner


Scanner class is defined in java.util package, so first step is to import this class in your Java program. Once you imported this class, you can create 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. Scanner provides a method called hasNextLine() which returns true if file has one more line to read.

This check is 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. You can read data from file by calling nextLine() method, this will return the next line and advance the file pointer to next line. This method return a String object representing a line in file. You can use a while() loop as shown in our first example, to read all lines from file 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.

Oracle Java Tutorial and Materials, Oracle Java Prep, Oracle Java Guides

Solution 2 - Reading File using BufferedReader


BufferedReader provides another way to read file line by line in Java. It follows 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 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 readLine() method to read the next line from file. This method return a String object containing data from 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 buffered reader here, you should do it on your real production code, as suggested earlier on right way to close streams in Java. Its better to call close() method on finally block. If you are on Java 7, consider using try-with-resource statement to automatically close resources once you are done with it.

Oracle Java Tutorial and Materials, Oracle Java Prep, Oracle Java Guides

Java Program to read a file in Java


Here is our complete Java program to read a file in Java. This program contains two examples, first example shows how to read a text file using Scanner class and 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 it. If you are coding in Eclipse then don't worry, Eclipse will take care of it. In order to run this program from command line,  create a  Java source file with name FileReaderDemo.java and write this program there. Once you are done with it, you can follow steps given on how to run Helloworld in Java to run this program from 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://oraclejavacertified.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 is you are running on Java 1.4. You can use Files class to read text files form Java 7 onward. 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 platform's character encoding.

Related Posts

0 comments:

Post a Comment