Java Reference
In-Depth Information
If you want to read an entire line of text at a time instead of reading a file character by
character, you can use the BufferedReader class in conjunction with a FileReader .
The BufferedReader class reads a character input stream and buffers it for better effi-
ciency. You must have an existing Reader object of some kind to create a buffered ver-
sion. The following constructors can be used to create a BufferedReader :
BufferedReader( Reader ) —Creates a buffered character stream associated with
the specified Reader object, such as FileReader
n
BufferedReader( Reader , int ) —Creates a buffered character stream associated
with the specified Reader and with a buffer of int size
n
A buffered character stream can be read using the read() and read( char[] , int , int )
methods described for FileReader . You can read a line of text using the readLine()
method.
The readLine() method returns a String object containing the next line of text on the
stream, not including the character or characters that represent the end of a line. If the
end of the stream is reached, the value of the string returned will be equal to null .
An end-of-line is indicated by any of the following:
A newline character ( '\n' )
n
A carriage return character ( '\r' )
n
A carriage return followed by a newline (“\n\r”)
n
The project contained in Listing 15.7 is a Java application that reads its own source file
through a buffered character stream.
LISTING 15.7
The Full Text of SourceReader.java
1: import java.io.*;
2:
3: public class SourceReader {
4: public static void main(String[] arguments) {
5: try {
6: FileReader file = new
7: FileReader(“SourceReader.java”);
8: BufferedReader buff = new
9: BufferedReader(file);
10: boolean eof = false;
11: while (!eof) {
12: String line = buff.readLine();
13: if (line == null)
Search WWH ::




Custom Search