Sitemap
Swati Sinha

Swati Sinha

Member-only story

Java File Read

1 min readAug 30, 2024

A very interesting and easy approach to provide solutions on File- Read. We used this frequently whenever a requirement on File Read and Write is required.

Press enter or click to view image in full size
Photo by Aaron Burden on Unsplash

BufferedReader — It is the package from java.io that reads the text from the file by reading the text from character input stream. It is often used for efficient reading of text files.

public class FileReadWriteExample {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new FileReader("Test.txt"));
try {
while (br.ready()) {
System.out.println(br.readLine());
}
} finally {
br.close();
}

}
Response from above -

Hello
Hi

Process finished with exit code 0

Follow the below steps to read a file -

  1. Import the java.io package
  2. Create a FileReader object to open the file. Test.txt is the filename used in the above example . This file have the contents of Hello , Hi.
  3. Wrap the FileReader object with a BufferedReader for efficient reading.
  4. Use the readLine() method to read the file line by line.
  5. Close the BufferedReader to free up resources.

--

--