Read a file in Java

There are several ways to read a Java text file. Java supports different types of api to read file content. For example, read character by character, read line by line or read byte by by byte.



Read text file in Java

There are six ways to read a text file in Java.

  • Reading a text file using FileReader character by character
  • Reading a text file using FileReader line by line
  • Reading a text file using FileReader returns lines in a list
  • Reading a text file using FileInputStream by bytes
  • Reading a text file using Scanner
  • Reading a text file using NIO FileReader

Sample File

The sample file used in the post is data/test.txt. test.txt file contains the below text

This is a test file
This is second line


Reading a text file using FileReader character by character

The FileReader class is used in java to read a text file. FileReader is linked to BufferedReader to cache read file data for fast access. The read () operation is used to read the file by character until it reaches the end of the file. It is important to close the BufferedReader and FileReader connections. If the file is not available at the specified location or if there is no read permission or problem with accessing this file, an exception will be thrown.

package com.yawintutor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class JavaFileReaderChar {

	public static void main(String[] args) throws Exception {
		String content = readFile("data/test.txt");
		System.out.println(content);
	}

	public static String readFile(String fileName) throws Exception {
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader(new File(fileName));
			br = new BufferedReader(fr);
			StringBuffer sb = new StringBuffer();
			int ch = -1;
			while ((ch = br.read()) != -1) {
				sb.append((char) ch);
			}
			return sb.toString();
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		} finally {
			try {
				br.close();
			} catch (Exception e) {
			}
			try {
				fr.close();
			} catch (Exception e) {
			}
		}
	}
}

Output

This is a test file
This is second line


Reading a text file using FileReader line by line

In this example, the FileReader class is used to read the file. Here the data is read line by line. It reads until it receives the end of the line character or the end of the file character, and then sends to the program. Line by line is faster than reading character by character. This api will omit the end of the line character, and after calling readline() api, it is necessary to add a new line character.

package com.yawintutor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class JavaFileReaderLine {

	public static void main(String[] args) throws Exception {
		String content = readFile("data/test.txt");
		System.out.println(content);
	}

	public static String readFile(String fileName) throws Exception {
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader(new File(fileName));
			br = new BufferedReader(fr);
			StringBuffer sb = new StringBuffer();
			String str = null;
			while ((str = br.readLine()) != null) {
				sb.append(str).append("\n");
			}
			return sb.toString();
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		} finally {
			try {
				br.close();
			} catch (Exception e) {
			}
			try {
				fr.close();
			} catch (Exception e) {
			}
		}
	}
}

Output

This is a test file
This is second line


Reading a text file using FileReader returns lines in a list

FileReader class reads text file data line by line, and then adds to the String ArrayList. The list is sent at the end of the method. Before adding a line to the array list, a logic can be applied, so that the required data lines are available in the list.

package com.yawintutor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class JavaFileReaderLineList {

	public static void main(String[] args) throws Exception {
		List<String> content = readFile("data/test.txt");
		System.out.println(content);
	}

	public static List<String> readFile(String fileName) throws Exception {
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader(new File(fileName));
			br = new BufferedReader(fr);
			List<String> list = new ArrayList<String>();
			String str = null;
			while ((str = br.readLine()) != null) {
				list.add(str);
			}
			return list;
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		} finally {
			try {
				br.close();
			} catch (Exception e) {
			}
			try {
				fr.close();
			} catch (Exception e) {
			}
		}
	}
}

Output

[This is a test file, This is second line]


Reading a text file using FileInputStream by bytes

FileInputStream is another way to read Java file. It reads file content as a data stream. FileInputStream is mostly used for non- text files, such as image, video files where the content is not readable. These files are viewed using specialized applications.

package com.yawintutor;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

public class JavaFileStream {

	public static void main(String[] args) throws Exception {
		String content = readFile("data/test.txt");
		System.out.println(content);
	}

	public static String readFile(String fileName) throws Exception {
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		try {
			fis = new FileInputStream(new File(fileName));
			bis = new BufferedInputStream(fis);
			StringBuffer sb = new StringBuffer();
			int ch = -1;
			while ((ch = bis.read()) != -1) {
				sb.append((char) ch);
			}
			return sb.toString();
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		} finally {
			try {
				bis.close();
			} catch (Exception e) {
			}
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
	}
}

Output

This is a test file
This is second line


Reading a text file using Scanner

Another way to read a file is by using the Scanner class. The scanner class is used to read file data using the parsing logic.

package com.yawintutor;

import java.io.File;
import java.util.Scanner;

public class JavaFileReaderScanner {

	public static void main(String[] args) throws Exception {
		String content = readFile("data/test.txt");
		System.out.println(content);
	}

	public static String readFile(String fileName) throws Exception {
		Scanner sc = null;
		try {
			sc = new Scanner(new File(fileName));
			StringBuffer sb = new StringBuffer();
			while (sc.hasNextLine()) {
				sb.append(sc.nextLine()).append("\n");
			}
			return sb.toString();
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		} finally {
			try {
				sc.close();
			} catch (Exception e) {
			}
		}
	}
}

Output

This is a test file
This is second line


Reading a text file using NIO FileReader

The NIO package FileReader class is used to read file data over the network. When the data is received via the network, issues like network connectivity stop reading data. FileReader handles all kinds of network problems and ensures smooth reading of data from the file over the network.

package com.yawintutor;

import java.nio.file.Files;
import java.nio.file.Paths;

public class JavaFileReaderNIO {

	public static void main(String[] args) throws Exception {
		String content = readFile("data/test.txt");
		System.out.println(content);
	}

	public static String readFile(String fileName) throws Exception {
		try {
			return new String(Files.readAllBytes(Paths.get(fileName)));
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		}
	}
}

Output

This is a test file
This is second line



Related Articles

Leave a Reply

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