This article covers 3 ways to read a text file line by line :
Java NIO libraries – FileChannel to read the files. It is a non-blocking mode of reading files
BufferedReader – Which is a blocking operation i.e it blocks any other read/write request to the file until it has completed the task.
Apache Commons IO – FileUtils, simpler way to read files line by line. It is also a blocking operation.
The input file for each example is same as the one shown below:
src/com/mkyong/data.txt
1. Java NIO libraries
The example presents the simplest way of reading a small file. Since this is a small file, we directly allocate required memory to ByteBuffer using FileChannel size.
NIOFileReadExample.java
package com.mkyong;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileReadExample {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("src/com/mkyong/data.txt", "r");
FileChannel channel = file.getChannel();
System.out.println("File size is: " + channel.size());
ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
channel.read(buffer);
buffer.flip();//Restore buffer to position 0 to read it
System.out.println("Reading content and printing ... ");
for (int i = 0; i < channel.size(); i++) {
System.out.print((char) buffer.get());
channel.close();
file.close();
On executing the code you get the below output:
File size is: 19
Reading content and printing ...
2. BufferedReader
ReadTextFile.java
package com.mkyong;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
try {
File f = new File("src/com/mkyong/data.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
System.out.println("Reading file using Buffered Reader");
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
} catch (IOException e) {
e.printStackTrace();
The output on executing this code will be as shown below:
Reading file using Buffered Reader
3. Apache Commons IO
pom.xml
commons-io
commons-io
2.5
FileIOUtilsExample
package com.mkyong;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
try {
File f = new File("src/com/mkyong/data.txt");
System.out.println("Reading files using Apache IO:");
List lines = FileUtils.readLines(f, "UTF-8");
for (String line : lines) {
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
The output on executing above code will be:
Reading files using Apache IO:
References