Read Text File in Java (2024)
In this tutorial, we will demonstrate how to read Text File in Java.
What is the difference between BufferedReader and FileReader in Java?
Ans:
A FileReader object is passed as an input to a BufferedReader object, which has all of the necessary information about the text/csv file to be read.
BufferedReader br = new BufferedReader( new FileReader("sample.txt") );
When the BufferedReader object is given the "read" instruction, it utilises the FileReader object to read data from the file. When an input is provided, the FileReader object reads 2 (or 4) bytes at a time and returns the data to the BufferedReader, and the reader continues in this manner until it encounters the characters '\n' or '\r\n' (The end of the line symbol). The reader patiently waits until the order to buffer the next line is delivered after a line has been buffered.
//read each line of the file and buffer it
while((line = br.readLine()) != null)
Meanwhile, the BufferReader object allocates a specific memory location (on RAM) named "Buffer" in which it keeps all of the data obtained from the FileReader object.
Two ways to read in Text File in Java
Take a look at our Suggested Posts :
Java - Read text file using FileReader
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderUtility
{
public static void main(String[] args)
{
// use try-with-resource to close the reader automatically
try (FileReader fileReaderObj = new FileReader("c:\\testFile.txt"))
{
int line;
//read till end of file
while ((line = fileReaderObj.read()) != -1) {
//Print the file data
System.out.print((char) line);
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
Java - Read text file using BufferedReader
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderUtility
{
public static void main(String[] args)
{
// use try-with-resource to close the reader automatically
try (
BufferedReader bufferObj = new BufferedReader
(new FileReader("c:\\testFile.txt"))
)
{
String fileLine;
//read till end of file
while ((fileLine = bufferObj.readLine()) != null) {
//Print the file data
System.out.println(fileLine);
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
}