Java: How to read from a character based file using File Reader?
Java: How to read from a character based file using File Reader?
This article is part of a tutorial.
Tutorial Index page - Java File Read-Write
This article focuses on how to read from a character based file rather than binary files.
FileReader:
The Java SDK provides a very handy utility class called the FileReader (java.io.FileReader) to quickly access character based files. In the most simple case, all you need to is to instantiate the FileReader with a String which is the path to the file that you want to read. It is as simple as
FileReader fileReader = new FileReader(filePath); // throws FileNotFoundException
Note that instantiating a FileReader using a file path will throw a FileNotFoundException exception if the file itself does not exist, or is a directory/folder , or any other problems that might prevent the file from being accessed/read.
BufferedReader:
Once the FileReader is created with the file path, we are now ready to read the contents of the file. To do this we can use the BufferedReader (java.io.BufferedReader) class. A BufferedReader can be used a wrapper around the FileReader to read line by line. Without the BufferedReader and by just using the FileReader you could only read the File character by character.
So using a BufferedReader around the FileReader is a very efficient way of reading contents line by line from the FileReader.
Reading the file:
With the FileReader and the BufferedReader properly setup, all that is left is reading from the file. The code below is simple and self-explanatory.
// Read through the entire file String currentLineFromFile = bufferedReader.readLine(); // throws IOException while(currentLineFromFile != null) { // Add a carriage return (line break) to preserve the file formatting. textFromFile.append(carriageReturn + currentLineFromFile); currentLineFromFile = bufferedReader.readLine(); // throws IOException }
The above code uses a StringBuilder (textFromFile) to collect the contents of the file. With this code, all the contents of the file is collected into the StringBuilder which can be retrieved by textFromFile.toString()
Displaying the output:
The output from the StringBuilder can just be simple printed on the out stream by
System.out.println( textFromFile.toString());
Feedback or Questions?
We welcome feedback and questions and will try our best to attend to it as quickly as possible!
Please note that you would have to register before you can post in our forums and this is purely to guard us from the spam-bots. Be assured that we do not send spam mails and our website registration only takes minutes.
