5 Ways to Read a File in Java – BufferedReader, FileInputStream, Files, Scanner, RandomAccessFile

Filed Under: Java IO

There are many different ways to read a file in Java. In this tutorial, we will look into 5 different ways to read a file in Java.

Different Ways to Read a File in Java

The 5 classes from the Java IO API to read files are:

  1. BufferedReader
  2. FileInputStream
  3. Files
  4. Scanner
  5. RandomAccessFile

Reading Binary Files vs Text Files

  • The FileInputStream class reads the file data into a stream of bytes. So it should be used for binary files such as image, pdf, media, videos, etc.
  • Text files are character based. We can use Reader classes as well as Stream classes to read them.
  • Files and Scanner classes can be used to read text files, not binary files.

Let’s look into the example programs to read a file in Java.

1. BufferedReader Read File

We can use BufferedReader to read the text file contents into char array.

BufferedReader is efficient for reading the file because it buffers the input from the specified file. Without buffering, each invocation of the read() or readLine() methods will read bytes from the file, then converted into characters and returned, which will be very inefficient.

package com.journaldev.io.readfile;

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

public class ReadFileUsingBufferedReader {

	public static void main(String[] args) {
		BufferedReader reader;
		char[] buffer = new char[10];
		try {
			reader = new BufferedReader(new FileReader(
					"/Users/pankaj/Downloads/myfile.txt"));
			while (reader.read(buffer) != -1) {
				System.out.print(new String(buffer));
				buffer = new char[10];
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

In the above program, I am printing the file data to console. Let’s look at another utility class to perform read file operations.

  1. Read complete file as String
  2. Read file line by line and return list of String
  3. Count the occurrence of a String in the given file.
package com.journaldev.java;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ReadFileJavaExample {

	/**
	 * Main function to invoke different functions to
	 * 1. readCompleteFileAsString - Read complete file as String
	 * 2. readFileToListOfLines - Read lines from file and return list of line String
	 * 3. countStringInFile - Count occurrence of a String in the file
	 * @param args
	 */
	public static void main(String[] args) {

		String filePath = "/Users/pankaj/Downloads/myfile.txt";

		String str="Java";

		String fileData = readCompleteFileAsString(filePath);

		System.out.println("Complete File Data:"+fileData);

		List<String> linesData = readFileToListOfLines(filePath);

		if(linesData!=null){
			for(int i=0; i<linesData.size(); i++){
				System.out.println("Line "+i+": "+linesData.get(i));
			}
		}

		int count = countStringInFile(filePath,str);

		System.out.println("String "+str+" found "+count+" times in the given file");

	}

	/**
	 * This function will count the number of times given String appears in the file
	 * @param filePath
	 * @param string
	 * @return
	 */
	private static int countStringInFile(String filePath, String str) {
		if(filePath == null || filePath == "" || str == null || str == "") return 0;
		int count=0;
		int searchStrLength = str.length();
		BufferedReader reader;
		try {
			reader = new BufferedReader(
			        new FileReader(filePath));
		} catch (FileNotFoundException e) {
			System.out.println("File is not present in the classpath or given location.");
			return 0;
		}
		String line;
		 try {
			while ((line=reader.readLine()) != null) {
				for(int i=0;i<line.length();) {
					int index=line.indexOf(str,i);
					if(index!=-1) {
						count++;
						i+=index+searchStrLength;
					} else {
						break;
					}
				}
			 }
		} catch (IOException e) {
			System.out.println("IOException in reading data from file.");
			return 0;
		}
		try {
			reader.close();
		} catch (IOException e) {
			System.out.println("IOException in closing the Buffered Reader.");
			return count;
		}
		return count;
	}

	/**
	 * This function will read file line by line and return the data in form of a list of String
	 * @param filePath
	 * @return
	 */
	private static List<String> readFileToListOfLines(String filePath) {
		List<String> linesData = new ArrayList<String>();
		BufferedReader reader;
		try {
			reader = new BufferedReader(
			        new FileReader(filePath));
		} catch (FileNotFoundException e) {
			System.out.println("File is not present in the classpath or given location.");
			return null;
		}
		String line;
		 try {
			while ((line=reader.readLine()) != null) {
				 linesData.add(line);
			 }
		} catch (IOException e) {
			System.out.println("IOException in reading data from file.");
			return null;
		}
		try {
			reader.close();
		} catch (IOException e) {
			System.out.println("IOException in closing the Buffered Reader.");
			return null;
		}
		return linesData;
	}

	/**
	 * This function will read complete file and return it as String
	 * @param filePath
	 * @return
	 */
	private static String readCompleteFileAsString(String filePath) {

		StringBuilder fileData = new StringBuilder();
		BufferedReader reader;
		try {
			reader = new BufferedReader(
			        new FileReader(filePath));
		} catch (FileNotFoundException e) {
			System.out.println("File is not present in the classpath or given location.");
			return null;
		}
		char[] buf = new char[1024];
        int numRead=0;
        try {
			while((numRead=reader.read(buf)) != -1){
			    String readData = String.valueOf(buf, 0, numRead);
			    fileData.append(readData);
			    buf = new char[1024];
			}
		} catch (IOException e) {
			System.out.println("IOException in reading data from file.");
			return null;
		}
        try {
			reader.close();
		} catch (IOException e) {
			System.out.println("IOException in closing the Buffered Reader.");
			return null;
		}
		return fileData.toString();
	}

}

2. FileInputStream – Read Binary Files to Bytes

We should always use Stream for reading non-character based files such as image, videos, etc.

package com.journaldev.io.readfile;

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

public class ReadFileUsingFileInputStream {

	public static void main(String[] args) {
		FileInputStream fis;
		byte[] buffer = new byte[10];

		try {
			fis = new FileInputStream("/Users/pankaj/Downloads/myfile.txt");
			while (fis.read(buffer) != -1) {
				System.out.print(new String(buffer));
				buffer = new byte[10];
			}
			fis.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

The FileInputStream read operation is used with byte array whereas BufferedReader read operation uses char array.

3. Files – Read File to List of Strings

Files is a utility class that was introduced in Java 1.7 release. We can use its readAllLines() method to read text file data as a list of string.

package com.journaldev.io.readfile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class ReadFileUsingFiles {

	public static void main(String[] args) {
		try {
			List<String> allLines = Files.readAllLines(Paths.get("/Users/pankaj/Downloads/myfile.txt"));
			for (String line : allLines) {
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

4. Scanner – Read Text File as Iterator

We can use Scanner class to read text file. It works as an iterato

package com.journaldev.io.readfile;

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

public class ReadFileUsingScanner {

	public static void main(String[] args) {
		try {
			Scanner scanner = new Scanner(new File("/Users/pankaj/Downloads/myfile.txt"));
			while (scanner.hasNextLine()) {
				System.out.println(scanner.nextLine());
			}
			scanner.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

}

5. RandomAccessFile – Reading Files in Read-Only Mode

The RandomAccessFile class allows us to read file in different modes. It’s a good option when you want to make sure that no accidental write operation is performed on the file.

package com.journaldev.io.readfile;

import java.io.IOException;
import java.io.RandomAccessFile;

public class ReadFileUsingRandomAccessFile {

	public static void main(String[] args) {
		try {
			RandomAccessFile file = new RandomAccessFile("/Users/pankaj/Downloads/myfile.txt", "r");
			String str;
			while ((str = file.readLine()) != null) {
				System.out.println(str);
			}
			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

That’s all for reading a file in Java using various classes from Java IO API.

You can download all the example code from our GitHub Repository.

References:

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages