Java :Different ways of Reading a text file


There are multiple ways of reading a text file in Java as below:

  1. BufferedReader
  2. FileReader
  3. Scanner
  4. Stream/Files (java 8): Read all file lines
  5. Paths (Java 8) : Read text file as String

Every way have something different as BufferedReader provides buffering of data for fast reading and Scanner provides parsing ability while we can use both BufferedReader and Scanner to read a text file line by line in Java.

Java 8 introduced Stream class java.util.stream which provides a lazy and more efficient way to read a file.

File Reading By BufferedReader

This method reads text from a character-input stream. It does buffering for efficient reading of characters, arrays, and lines.The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,


BufferedReader in = new BufferedReader(Reader in, int size);
try {
    File file = new File(FILE);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String st;
    while ((st = br.readLine()) != null)
	System.out.println(st);
} catch (IOException ex) {
	ex.printStackTrace();
}

Note : In below code examples not follow usual practices of writing good code like flushing/closing streams, Exception-Handling etc, to reduce number of lines code for better understanding.

File Reading By FileReader

FileReader is convenient class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.


Constructors defined in this class are:
FileReader(File file) : Creates a new FileReader, given the File to read from.

FileReader(FileDescriptor fd): Creates a new FileReader, given the FileDescriptor to read from.

FileReader(String fileName): Creates a new FileReader, given the name of the file to read from.
try {
     FileReader fr = new FileReader(FILE);

     int i;
     while ((i = fr.read()) != -1)
	System.out.print((char) i);
} catch (IOException ex) {
	ex.printStackTrace();
}

File Reading By Scanner

A scanner can parse primitive types and strings using regular expressions and breaks its input into tokens using a delimiter pattern, which by default matches white space. The resulting tokens may then be converted into values of different types using the various next methods.

try {
	File file = new File(FILE);
	Scanner sc = new Scanner(file);

	while (sc.hasNextLine())
	System.out.println(sc.nextLine());
	} catch (Exception ex) {
	ex.printStackTrace();
	}

Read file by scanner without loop

File file = new File(FILE);
try {
	Scanner sc = new Scanner(file);
	// Use delimiter \Z for next line
	sc.useDelimiter("\Z");

	System.out.println(sc.next());
} catch (Exception ex) {
	ex.printStackTrace();
}

File Reading By Stream (Java8)

Files.readAllLines() method read all lines from a file and ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.
Bytes from the file are decoded into characters using the specified charset.


public static List readAllLines(Path path,Charset cs)throws IOException

This method recognizes the following as line terminators:
CARRIAGE RETURN followed by LINE FEED (u000D followed by u000A)
u000A, LINE FEED
u000D, CARRIAGE RETURN
List<String> lines = Collections.emptyList();
		try {
			lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8);
			Iterator<String> itr = lines.iterator();
			while (itr.hasNext())
				System.out.println(itr.next());
		} catch (IOException e) {
			e.printStackTrace();
		}

File Reading By Paths (Java8)

try {
			String data = new String(Files.readAllBytes(Paths.get(FILE)));
			System.out.println(data);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

Complete Example

In below example  covered all the above cases.

Test Data


Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
package com.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class FileReadingWay {
	private static final String FILE = "C:\Users\saurabh.gupta1\Desktop\Test Data.java";

	public static void main(String[] args) {
		FileReadingWay s = new FileReadingWay();
		System.out.println("===============Read File By Buffered Reader================");
		s.readFileByBufferedReader();
		System.out.println("===============Read File By File Reader================");
		s.readFileByFileReader();
		System.out.println("===============Read File By Scanner================");
		s.readFileByScanner();
		System.out.println("===============Read File By Scanner without Loop================");
		s.readFileByScannerWithOutLoop();
		System.out.println("===============Read All Files================");
		s.readFileByReadAllFiles();
		System.out.println("===============Read Text File and String================");
		s.readTextFileAsString();
	}

	private void readFileByBufferedReader() {
		try {
			File file = new File(FILE);

			BufferedReader br = new BufferedReader(new FileReader(file));

			String st;
			while ((st = br.readLine()) != null)
				System.out.println(st);
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	private void readFileByFileReader() {
		System.out.println();
		try {
			FileReader fr = new FileReader(FILE);

			int i;
			while ((i = fr.read()) != -1)
				System.out.print((char) i);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		System.out.println();
	}

	private void readFileByScanner() {

		try {
			File file = new File(FILE);
			Scanner sc = new Scanner(file);

			while (sc.hasNextLine())
				System.out.println(sc.nextLine());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void readFileByScannerWithOutLoop() {
		File file = new File(FILE);
		try {
			Scanner sc = new Scanner(file);
			// Use delimiter \Z for next line
			sc.useDelimiter("\Z");

			System.out.println(sc.next());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void readFileByReadAllFiles() {
		List<String> lines = Collections.emptyList();
		try {
			lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8);
			Iterator<String> itr = lines.iterator();
			while (itr.hasNext())
				System.out.println(itr.next());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void readTextFileAsString() {
		try {
			String data = new String(Files.readAllBytes(Paths.get(FILE)));
			System.out.println(data);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

Output


===============Read File By Buffered Reader================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By File Reader================

Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By Scanner================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By Scanner without Loop================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read All Files================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read Text File and String================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 

References

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s