Java Read File

Filed Under: Java
java read file, read file in java

Today we will look into different ways to read a file in Java program.

Java Read File

java read file, read file in java

Reading a file in java is a very common operation. It comes under Java IO and there are many classes to read file in java.

We will look into following classes for java read file program.

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

FileInputStream reads the file data in bytes, so it should be used for files such as image, pdf, media, video documents etc.

If you want to read a text file that is char based, then you can use any of the Reader classes or the utility classes mentioned above.

Let’s look at some example programs to read a file in java.

1. BufferedReader

We can use BufferedReader to read file data into char array.

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

Below is a simple program showing java read file using BufferedReader read method.


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 file data to console. Below is another utility class to perform following 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 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

Always use Stream for reading non-character based files such as image, video etc. You can use the below program to read a file in java using FileInputStream.


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();
		}
	}

}

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

3. Files

Files is a utility class introduced in Java 1.7. We can use its readAllLines method to read text file data as 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

We can also use Scanner for java read file operations. You can use this for reading the text-based file only.


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

RandomAccessFile allow us to read file in different mode. It’s a good option when you want to make sure that no accidental write operation is performed on the file. Below is a simple java read file example using RandomAccessFile.


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 java read file examples using different methods.

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