Java Reference
In-Depth Information
or writer and set the size of the buffer. If the size is not set, the default size of 8,192
characters is used:
public BufferedReader ( Reader in , int bufferSize )
public BufferedReader ( Reader in )
public BufferedWriter ( Writer out )
public BufferedWriter ( Writer out , int bufferSize )
For example, the earlier getMacCyrillicString() example was less than efficient be‐
cause it read characters one at a time. Because MacCyrillic is a 1-byte character set, it
also read bytes one at a time. However, it's straightforward to make it run faster by
chaining a BufferedReader to the InputStreamReader , like this:
public static String getMacCyrillicString ( InputStream in )
throws IOException {
Reader r = new InputStreamReader ( in , "MacCyrillic" );
r = new BufferedReader ( r , 1024 );
StringBuilder sb = new StringBuilder ();
int c ;
while (( c = r . read ()) != - 1 ) sb . append (( char ) c );
return sb . toString ();
}
All that was needed to buffer this method was one additional line of code. None of the
rest of the algorithm had to change, because the only InputStreamReader methods used
were the read() and close() methods declared in the Reader superclass and shared by
all Reader subclasses, including BufferedReader .
The BufferedReader class also has a readLine() method that reads a single line of text
and returns it as a string:
public String readLine () throws IOException
This method replaces the deprecated readLine() method in DataInputStream , and it
has mostly the same behavior as that method. The big difference is that by chaining a
BufferedReader to an InputStreamReader , you can correctly read lines in character
sets other than the default encoding for the platform.
The BufferedWriter() class adds one new method not included in its superclass, called
newLine() , also geared toward writing lines:
public void newLine () throws IOException
This method inserts a platform-dependent line-separator string into the output. The
line.separator system property determines exactly what the string is: probably a line‐
feed on Unix and Mac OS X, and a carriage return/linefeed pair on Windows. Because
network protocols generally specify the required line terminator, you should not use
this method for network programming. Instead, explicitly write the line terminator the
Search WWH ::




Custom Search