- Home
- Objectives

- XyzWs Study Guides
- Study Guides
- Study Notes
- Resources

- Mock Exams
SCJP Study Guide:
API Contents
Printer-friendly version |
Mail this to a friend
BufferedReader and BufferedWriter
java.io.BufferedReader
The java.io.BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example:
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.
Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
BufferedReader Constructors:
- public BufferedReader(Reader in) creates a buffering character-input stream that uses a default-sized input buffer.
- public BufferedReader(Reader in, int sz) creates a buffering character-input stream that uses an input buffer of the specified size. If sz is <= 0 then an IllegalArgumentException exception will be thrown.
The constructor takes a Reader as the parameter, since FileReader is a Reader it is the correct type for the parameter:
BufferedReader br = new BufferedReader(new FileReader("foo.in"));
Reading Methods:
- public int read() throws IOException : Read a single character . Returns the character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached.
- public int read(char[] cbuf,int off, int len) throws IOException : Read characters into a portion of an array.
- public String readLine() throws IOException : Read a line of text. 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 linefeed. 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.
Misc Methods:
- public boolean ready() throws IOException : Tests whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready. Returns true if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block.
- public boolean markSupported() : Tests whether this stream supports the mark() operation, which it does. Returns true if and only if this stream supports the mark operation. public void reset() throws IOException : Resets the stream to the most recent mark. An IOException exception will be thrown if the stream has never been marked, or if the mark has been invalidated.
- public void mark(int readAheadLimit) throws IOException : Marks the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point. The readAheadLimit limits on the number of characters that may be read while still preserving the mark. After reading this many characters, attempting to reset the stream may fail. A limit value larger than the size of the input buffer will cause a new buffer to be allocated whose size is no smaller than limit. Therefore large values should be used with care. An IllegalArgumentException will be thrown if readAheadLimit is < 0. An IOException will be thrown if an I/O error occurs
- public long skip(long n) throws IOException : Skips the number n of characters.Returns the number of characters actually skipped An IllegalArgumentException will be thrown if n is negative. An IOException will be thrown if an I/O error occurs.
- public boolean ready() throws IOException : Tests whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready. Returns True if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block. An IOException will be thrown if an I/O error occurs.
Creating an instance of BufferedReader allocates memory storage for data input. The primary need for BufferedsReader is that it makes data input, which could be a very inefficient process into a more efficient process. "In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream." This could lead to many reading steps, and reading is one of the slowest aspects of computer processing. The Buffered reader allows for one reading step by providing data input storage which can then be accessed efficiently.
java.io.BufferedWriter
The java.io.BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.
A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.
In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
The BufferedWriter Class Constructors
- public BufferedWriter(Writer out) creates a buffered character-output stream that uses a default-sized output buffer.
- public BufferedWriter(Writer out, int sz) - creates a new buffered character-output stream that uses an output buffer of the given size. The sz (Output-buffer size) must be a positive integer. If sz is <= 0 then an IllegalArgumentException exception will be thrown.
Writing Methods:
- public void write(int c) throws IOException : Writes a single character.
- public void write(char[] cbuf,int off, int len) throws IOException : Writes a portion of an array of characters. Ordinarily this method stores characters from the given array into this stream's buffer, flushing the buffer to the underlying stream as needed. If the requested length is at least as large as the buffer, however, then this method will flush the buffer and write the characters directly to the underlying stream. Thus redundant BufferedWriters will not copy data unnecessarily.
- public void write(String s, int off, int len) throws IOException : Writes a portion of a String. If the value of the len parameter is negative then no characters are written. This is contrary to the specification of this method in the superclass, which requires that an IndexOutOfBoundsException be thrown.
- public void newLine() throws IOException : Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.
Misc Methods:
- public void flush() throws IOException : Flushs the stream.
- public void close() throws IOException : Closes the stream.
Creating an instance of BufferedWriter allocates memory storage for data output. The primary need for BufferedsWritter is that it makes data ouput, which could be a very inefficient process into a more efficient process. In general, each read request made of a FileWriter causes a corresponding write request to be made of the underlying character or byte stream." This could lead to many writing steps, and writing is one of the slowest aspects of computer processing. The BufferedWritter allows for one writing step by providing data output storage which can then be outputted efficiently.
java.io.PrintWriter
Print formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().
The class PrintWriter is used to deal with the end-of-line problem
and other frustrations of file output. PrintWriter provides many
methods that are useful for "printing" characters. ("Printing" in this context
means sending characters to an output destination, not usually a hard-copy
printer.) The println() method uses the approprate line separator
for the operating system the program is running on.
Often a PrintWriter stream is connected to a BufferedWriter stream which is
connected to a FileWriter. A further advantage of PrintWriter is
that none of its methods (including println()) throw exceptions.
Usually output is more reliable than input (because the program has control
over its output), so exception handling is sometimes not needed.
Examples
The following program uses BufferedReader and BufferedWriter to copy the contents of a file named input.txt into a file called output.txt :
import java.io.*;
public class CopyFile {
public static void main(String[] args) throws IOException {
try {
//Create a FileReader object
File inputFile = new File("input.txt");
BufferedReader br = new BufferedReader(new FileReader(inputFile));
//Create a FileWriter object
File outputFile = new File("output.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
//Copy contents
int c;
while ((c = br.read()) != -1)
bw.write(c);
//Clear up
br.close();
bw.close();
} catch(IOException e) {}
}
}
This program is very simple. It opens a BufferedReader on input.txt and opens a BufferedWriter on output.txt. The program reads characters from the reader as long as there's more input in the input file. When the input runs out, the program closes both the reader and the writer.
The following example code uses FileWriter and PrintWriter:
import java.io.*;
class WriteTextFile
{
public static void main ( String[] args )
{
String fileName = "output.txt" ;
PrintWriter print = null;
try
{
print = new PrintWriter( new BufferedWriter( new FileWriter( fileName ) ) );
}
catch ( IOException e)
{
...
}
print.println( "Line1..........!" );
print.println( "Line2..........!" );
print.println( "Line3..........!" );
print.println( "Line4..........!" );
print.close();
}
}
http://www.nakov.com/inetjava/lectures/part-1-sockets/InetJava-1.2-Java-IO.html