How to Read Text File in Java

In java applications, sometimes we need to read a text file and process it into something meaningful. There are multiple ways through which we can read text files for e.g FileReader, BufferedReader or Scanner.To read a text file line by line we can use BufferedReader or Scanner.

Below are the different ways of reading a text file in java :

1.  FileReader : It is convenient for text files in the system's default encoding.

2. FileInputStream : Files that contain weird characters.Files can be binary or text.

Reading Text Files in Java

Use FileReader if you want to read an ordinary text file in the system's default encoding, and wrapped it in a BufferedReader.

In the following example, we read the input file called 'test.txt' and prints the output on the console line by line. 


public class ReadTextFile {
    public static void main(String [] args) {

        // The name of the file to open.
        String fileName = "temp.txt";

        // This will reference one line at a time
        String line = null;

        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileName);

            // Wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null) {
            // Close file
        catch(FileNotFoundException ex) {
                "Unable to open file '" + 
                fileName + "'");                
        catch(IOException ex) {
                "Error reading file '" 
                + fileName + "'");                  
            // Or we could just do this: 
            // ex.printStackTrace();

Please mention in the comments if you have any questions regarding how to read text file in java.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry