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.
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 -
Import the java.io package
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.
Wrap the FileReader object with a BufferedReader for efficient reading.
Use the readLine() method to read the file line by line.