Java read file

There are many ways to read a file in Java. DataInputStream class is used to read text File line by line. BufferedReader is also used to read a file in Java when the file in huge. It is wrapped around FileReader. Java supports reading from a Binary file using InputStream.

Java read file

There are many ways to read a file in Java. DataInputStream class is used to read text File line by line. BufferedReader is also used to read a file in Java when the file in huge. It is wrapped around FileReader. Java supports reading from a Binary file using InputStream.

Java read file


There are many ways to read a file in Java. DataInputStream class is used to read text File line by line. BufferedReader is also used to read a file in Java when the file in huge. It is wrapped around FileReader. Java supports reading from a Binary file using InputStream.

Close() method must be called every time.

Class DataInputStream

DataInputStream reads data types from input stream like FileInputStream. DataInputStream is not safe while accessing multithreads. FileInputStream is used for reading streams of raw bytes.

BufferedReader

BufferedReader class read text from a character-input stream rather than read one character, arrays, and lines at a time.

Using BufferedReader makes works faster as it reads a larger block rather than reading one character at a time.

Buffer size may be specified. BufferedReader must be wrapped around read() like such as FileReaders, InputStreamReaders and StringBuilder.

BufferedReader br = new BufferedReader(new InputStreamReader(in));

readline() is used to read the next line.

Example of Java Read File:

package FileHandling;

import java.io.BufferedReader;
import java.io.DataInputStream;

import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileReadTest {
	public static void main(String[] args) {

		try {

			FileInputStream fileInputStream = new FileInputStream("C:/file.txt");
			DataInputStream in = new DataInputStream(fileInputStream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String string;
			while ((string = br.readLine()) != null) {
				System.out.println(string);
			}
			in.close();
		} catch (Exception e) {
			System.err.println(e);
		}
	}
}