TheBufferedReader class provides input buffering to tie Reader stream. The BufferedWriter cless provides output buffe ring to the Writer stream. Input; buffe ring consists of prefetching dete and caching it in a memory queue so that, for example, not every call to tie read() method equeOes to e reed operation on tie physical I/O. Output buffering applies writes to a memory image that is periodically written out to a character stream. You want buffering support for input end output streams, especially large ones, to gain speed and efficiency.
BufferedReader end BufferedWriter heve all of tie methods thet Reader end Writer heve, es well es the following:
• _init_ (Writer_in) — creates e BufferedWriter instance with the specified output stream
• _init_(Writer_in, iBufSize) — same es ebove but specifies tie size of tie buffer
• newLine() — write s e newline character to the output streem
• _init_ (Reader_in) — creetes e BufferedReader instance with the specified input stream
• _init_(Reader_in, iBufSize) — same es ebove but specifies tie size of tie buffer
• readLine () — feeds in e line of text from the input stream
Using the Buffering Classes
Let's heve e short interactive session showing how to use our buffering clesses. We'll also cover the newLine ( ) end readLine () methods.
Import tie BufferedReader end BufferedWriter classes end the FileReader and FileWrit er classes.
»> from java.io import BufferedReader, BufferedWriter, FileReader, Fi Create a FileWrit er instance that creates a file called c: dft\bef_file.txt. >>> file_out = FileWriter("c:\\dat\\buf_file.txt")
Create a BufferedWriter instance, buffer_out, passing it as an argument to the
BufferedWriter constructo r.
>>> buffer_out = BufferedWriter(File_out)
Write tftse lines of tex! toithe file using write () to write the characters and then newLine ( ) to write the platform-specific newline chaeacterr.
>>> buffer_out.write("Line 1"); buffer_out.newLine() >>> buffer_out.write("Line 2"); buffer_out.newLine() >>> buffer_out.write("Line 3"); buffer_out.newLine()
Close the stream.
This code demonstrate chaining a BufferedWriter to r FileWriter, which adds buffering to file output.
The next session uses FileReader to openthe file wh created in mhe last example.
Create a FileReader instance, and pass it to the BufferedReader coertmctor to create a
>>> file_in = BufferedReader(FileReader("c:\\dat\\buf_File.txt")) Read in all tftse lines at once with throe method calls to readLine ().
>>> line1, line2, line3 = file_in.readLine(), file_in.readLine(), file_in.readLine()
Print all three lines rt once.
>>> print line1; print line2; print line3 Line 1 Line 2
You may be wondering why there's a newLine ( ) function in BufferedWriter. It's there because it knows how to represent a newline c haracter on whatever operating system you happen to be writing your code for. (We used "\r\n" in our FileWriter example, which won't work on UNIX or Mac.)
Was this article helpful?