There are multiple ways to read a file in Java e.g. you can use a Scanner as we have seen in the last example, or you can use the BufferedReader class. The advantage of using a BufferedReader to read a text file is speed. It allows faster reading because of internal buffering provided by BufferedReader. Other Reader classes like FileReader access the file or disk every time you call the read() method but BufferedReader keeps 8KB worth of data in its internal buffer which you can read it without accessing the file multiple times. It's loaded when you access the file the first time for a subsequent read.
The BufferedReader class is also a good example of a Decorator design pattern because it decorates existing readers e.g. FileReader to provide buffering, remember, the reading from file functionality still comes from the FileReader class.
One more advantage of using the BufferedReader for reading a text file is its ability to read the file line by line. It provides a readLine() method which can be used to read a text file line by line in Java.
The java.io.BufferedReader class provides 4 versions of the read() method to read data from a text file
Btw, from Java 8 onwards there are many ways to read a file line by line in Java e.g. you can use Files.lines() method to get all lines as Stream in Java and then you cannot only read them line by line but also you can also use Stream operations e.g. map(), flatMap(), filter(), etc to perform useful operations.
If you are not familiar with functional programming and Java 8 see these Java 8 tutorials to learn more about the basics of functional programming with Java 8 syntax.
If you notice carefully, while converting the character array to String, we have correctly used the offset and length because it might be possible that the array which you are using for storing content, may content dirty data from the previous read, as we are not cleaning it up after every read.
One more advantage of using the BufferedReader for reading a text file is its ability to read the file line by line. It provides a readLine() method which can be used to read a text file line by line in Java.
The java.io.BufferedReader class provides 4 versions of the read() method to read data from a text file
- read() - to read a single character, this method returns an int, so you need to cast that to a character
- read(char[] cbuf) - to read characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. This method either returns the number of characters read or -1 if the end of the file has been reached. The method comes from the Reader class.
- read(CharBuffer cbuffer) - to read characters into a CharBuffer, this is similar to the previous method except that it reads characters into a CharBuffer object instead of the array. This method also returns a total number of characters read or -1 if the end of the file has been reached. This method also belongs to java.io.Reader class.
- read(char[] cbuf, int off, int len) - to read characters into an array but gives you control where to store the characters read from a file. You can specify offset i.e. the indices to start and length, how many characters to store.
- readLine() - to read a line of text. You can use this method to read a file line by line in Java. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a line feed. This method returns a string containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached. Many Java developer uses BufferedReader class just for this method.
Btw, from Java 8 onwards there are many ways to read a file line by line in Java e.g. you can use Files.lines() method to get all lines as Stream in Java and then you cannot only read them line by line but also you can also use Stream operations e.g. map(), flatMap(), filter(), etc to perform useful operations.
If you are not familiar with functional programming and Java 8 see these Java 8 tutorials to learn more about the basics of functional programming with Java 8 syntax.
How to read a text file using FileReader and BufferedReader
Here is our sample Java program to read a plain text file using BufferedReader. In this program, I have shown two examples of BufferedReader class, the first one reads file content into a character array and the second one reads the text file line by line.If you notice carefully, while converting the character array to String, we have correctly used the offset and length because it might be possible that the array which you are using for storing content, may content dirty data from the previous read, as we are not cleaning it up after every read.
That's the advantage of using offset and length, you don't need to clear or clean the array. You can further see these free Java courses to learn more about file reading in Java.
Java BufferedReader Example
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /* * Java Program read a text file using BufferedReader. * It allows you to read file line by line or directly * into a character array. */ public class BufferedReaderDemo { public static void main(String[] args) throws Exception { String filename = "newfile.txt"; // reading text file into array try { FileReader textFileReader = new FileReader(filename); BufferedReader bufReader = new BufferedReader(textFileReader); char[] buffer = new char[8096]; int numberOfCharsRead = bufReader.read(buffer); // read will be from // memory while (numberOfCharsRead != -1) { System.out.println(String.valueOf(buffer, 0, numberOfCharsRead)); numberOfCharsRead = textFileReader.read(buffer); } bufReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // reading file line by line using BufferedReader try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } } Output [first line] hello [second line] bye [first line] hello [second line] bye
You can see from the output that we have successfully read the text file. In the second example, since we have used the try-with-resource construct, you don't need to manually call the close() method of BufferedReader, it will automatically be called by Java. The catch clause is there to catch the IOException thrown by the close() method.
That's all about how to read a text file using BufferedReader in Java. As I said, there are two main reasons to use the BufferedReader class, first the buffering it provides which makes reading efficient, and second the readLine() method it gives, which allows you to read the text file line by line.
Related Java File tutorials you may like
- How to write to a file using BufferedWriter in Java? (solution)
- How to append text to a file in Java? (solution)
- 2 ways to read a text file in Java? (solution)
- How to read InputStream as Stream in Java? (example)
- How to load data from a CSV file in Java? (example)
- How to find the highest occurring word from a file in Java? (solution)
- How to read/write an XLSX file in Java? (solution)
P. S. - If you running in Java 8, you can also use streams to lazily read the file content by using the Files.lines() method which returns a Stream of String from a text file. You can then perform operations like map() and filter() on file content.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.