Java read file line by line

Java provides many different ways to read a text file line by line. This article explains various methods to read a text file in java with example programs and explanation.

Method 1: Using FileInputStream
Below is an example program of using a java fileinputstream to read a text file.

A fileinputstream can also be used to read binary files such as images, audio/video, keystore etc.

import java.io.FileInputStream;	
import java.io.IOException;

public class FileInputStreamExample {
   static void readUsingStream(String filePath) {
      FileInputStream fin = null;
      //initialize the input byte array
      byte[] buffer = new byte[1024];
      try {
        fin = new FileInputStream(new File(filePath));
        int i = 0;
        while ((i = fin.read(buffer)) != -1) {
          System.out.println(new String(buffer));
        }
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (fin != null) {
          try {
            fin.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
   }
}

Explanation
Initialize a java.io.FileInputStream with the source file as argument and a byte array which will hold all the bytes read by the stream.

Iterate over read() method till it returns -1 which means that the end of file has reached. In each iteration, the stream reads the bytes from the file and writes them to the buffer.

The buffer contents are converted to a String and written to console. At the end, do not forget to close the input stream.
Method 2: Using FileReader
Following example shows how to read a text file line by line with java.io.Filereader class.

import java.io.FileReader; 
import java.io.IOException;

public class FileReaderExample {	
   static void readUsingFileReader(String filePath) {
      FileReader fr = null;
      char[] buffer = new char[1024];
      try {
         fr = new FileReader(filePath);
         int i = 0;
         while ((i = fr.read(buffer)) != -1) {
            System.out.println(new String(buffer));
         }
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (fin != null) {
            try {
               fin.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }
}

Explanation
Initialize a java.io.FileReader with the source file as argument and a character array which will hold all the characters read by the stream.

Iterate over read() method till it returns -1 which means that the end of file has reached. In each iteration, the file reader reads the characters from the file and writes them to the buffer.

The characters from the buffer are converted to a String and written to console. At the end, do not forget to close the input reader.

Method 3: Using BufferedReader
java.io.BufferedReader class in java can be used to read a text file.

It has a readLine() method which reads an entire line of a file into a string. readLine() returns null when it has read the complete file or end of file is reached.

import java.io.BufferedReader;
import java.io.IOException;

public class BufferedReaderExample {	
   static void readUsingBufferedReader(String filePath) {
      BufferedReader br = null;
      try {
         br = new BufferedReader(new FileReader(filePath));
         String str = null;
         while ((str = br.readLine()) != null) {
            System.out.println(str);
         }
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (br != null) {
            try {
               br.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }
}

Explanation
Initialize a java.io.BufferedReader object which takes a java.io.FileReader object as argument which is linked to the original file.
Iterate over readLine() method till it returns null which means that the end of file has reached. At the end, do not forget to close the reader.
Method 4: Using Apache Commons library
This is another method to read a text file line by line in java using external library Apache Commons. Below is the example program.

import org.apache.commons.io.IOUtils;
import java.io.StringWriter;
import java.io.FileInputStream;

public class ApacheCommonsExample {	
   static void usingApacheCommons(String filePath) {
      FileInputStream fin = null;
      try {
         StringWriter writer = new StringWriter();
         fin = new FileInputStream(new File(filePath));
         IOUtils.copy(fin, writer);
         System.out.println(writer.toString());
      } catch (FileNotFoundException fne) {
         fne.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (fin != null) {
           try {
             fin.close();
           } catch (IOException e) {
             e.printStackTrace();
           }
        }
      }
   }
}

Explanation
Initialize a java.io.FileInputStream object with the source file as argument. copy() method of IOUtils from Apache commons library takes an input stream and writes it to a writer.

In this case we take a java.io.StringWriter. At the end, do not forget to close the input stream. This method requires Apache commons library to be on the classpath. Get it here
Method 5: Using java scanner
It is also possible to read a text file in java line by line using an object of scanner class in java. Example program follows.

import java.io.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ScannerExample {	
   static void usingScanner(String filePath) {
      FileInputStream fin = null;
      byte[] buffer = new byte[1024];
      Scanner scanner = null;
      try {
         fin = new FileInputStream(new File(filePath));
         scanner = new Scanner(fin);
         scanner.useDelimiter("\\n");
         while (scanner.hasNext()) {
          System.out.println(scanner.next());
         }
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } finally {
        if (scanner != null) {
          scanner.close();
        }
      }
   }
}

Explanation
Besides reading user input in java, scanner can also read a text files as shown above.
Initialize a java.io.FileInputStream with the source file as argument and a scanner object which is linked to this stream.

A new line character is set as the delimiter for this scanner. If this line is omitted or a new line character is not used then the scanner will split the output on a white space and each word will be printed on a new line.
At the end, do not forget to close the scanner.
Method 6: Using FileChannel (jdk 7 & above)
java.nio package introduced in java 7 can be utilized to read a file. Below is a demonstration followed by an explanation.

import java.nio.channels.FileChannel;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.io.FileNotFoundException;

public class FileChannelExample {
   static void usingChannel(String filePath) {
      RandomAccessFile fileAccess = null;
      FileChannel readChannel = null;
      try {
         fileAccess = new RandomAccessFile(new File(filePath), "r");
         readChannel = fileAccess.getChannel();
         ByteBuffer buffer = ByteBuffer.allocate(1024);
         while (readChannel.read(buffer) != -1) {
           buffer.flip();
           for (int i = 0; i < buffer.limit(); i++) {
             System.out.print((char) buffer.get(i));
           }
         }
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (fileAccess != null) {
           try {
             fileAccess.close();
           } catch (IOException e) {
             e.printStackTrace();
           }
         }
      }
   }
}

Explanation
Initialize a java.io.RandomAccessFile.RandomAccessFile with the source file as argument.

RandomAccessFile can be used to both read or write to a file.
It takes an operation mode along with the file path as argument during initialization. Since we want to read the file, we set the mode as “r”, which means read mode.
RamdomAccessFile opens a java.nio.channels.FileChannel through its getChannel() method.

FileChannel reads the data using its read() method and writes it to a java.nio.ByteBuffer.
FileChannel acts as a bridge between the file and storage buffer. Same buffer is used to hold the contents of file and for reading its contents.

This is done using buffer’s flip() method which resets the position of the buffer to 0. We extract the contents of the buffer in a loop and in every iteration a single byte is retrieved, converted to a character and written to the console.
At the end, do not forget to close the fileAccess.

Method 7: Using java 8 stream
Streams introduced in java 8 can be used to read a file line by line in a concise manner. Below is an example program to read a file in java 8.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class StreamExample{
   static void usingStram(String filePath) {
      try {
         Stream stream = Files.lines(Paths.get(filePath));
         stream.forEach((line) -> System.out.println(line));
         stream.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Explanation
For using a stream, first we need to get it. Use the static lines() method of java.nio.file.Files class to get a stream over the file.
File path is supplied to lines() as argument.

This stream can then be iterated over to read one line of a file at a time using its forEach method.
forEach method accepts a java.util.function.Consumer as argument. This is a functional interface having only one method and hence this method can be implemented using a Lambda expression.

Note : All the above methods write the output from the file to console but they may also be written to another file. Java provides different methods for writing a file.
Let’s tweak in :

1. All file reader and writer classes which directly interact with a file or a java.io.File object such as java.io.FileInputStreamjava.io.FileReader, java.io.FileOutputStream throw a java.io.FileNotFoundException since there is always a risk of file location being invalid (either the file is not present or the location denotes a directory).

2. All read() and write() methods throw a java.io.IOException since many kinds of errors may arise during both these operations such as file is corrupt, there are no write permissions, no disk space, file removed from its location etc.

3. java.io.FileInputStreamjava.io.FileReader both have constructors which take a java.io.File object or a file name in String format as arguments.

4. java.io.FileInputStream operates over bytes and is more suitable for binary files such as images, jars etc. while java.io.FileReader deals with characters and is more suitable for text files.

5. java.io.BufferedReader is faster as compared to java.io.FileInputStream and java.io.FileReaderas it reads a complete line in one go.

6. read() method of all reader classes returns -1 when there is nothing left to read.

7. Closing a java.io.BufferedReader closes the underlying java.io.Reader and there is no need to close it explicitly.
Similarly, closing a java.io.Scanner closes the underlying java.io.InputStream and there is no need to close it explicitly.
And closing java.io.RandomAccessFile also closes the underlying java.nio.channels.FileChannel

8. If you are using jdk 7 and above for development and declare the stream or reader objects as try(FileInputStream fin = new FileInputStream(new File(filePath))) and you don’t need to explicitly close the stream or reader.
This is called try-with-resources construct.

9. The default delimiter of scanner is a white space which means that it will split the input characters on a white space.
This article explained different methods of reading a text file in java. You can also read a CSV file or an excel file in java.
Hit the clap if the article was useful.

Leave a Reply

Your email address will not be published. Required fields are marked *