Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 19: Input/Output: Exploring java.io 583


CharArrayWriter( )
CharArrayWriter(intnumChars)

In the first form, a buffer with a default size is created. In the second, a buffer is created with a
size equal to that specified bynumChars.The buffer is held in thebuffield ofCharArrayWriter.
The buffer size will be increased automatically, if needed. The number of characters held by the
buffer is contained in thecountfield ofCharArrayWriter. Bothbufandcountare protected
fields.
The following example demonstratesCharArrayWriterby reworking the sample
program shown earlier forByteArrayOutputStream. It produces the same output as the
previous version.


// Demonstrate CharArrayWriter.
import java.io.*;


class CharArrayWriterDemo {
public static void main(String args[]) throws IOException {
CharArrayWriter f = new CharArrayWriter();
String s = "This should end up in the array";
char buf[] = new char[s.length()];


s.getChars(0, s.length(), buf, 0);
f.write(buf);
System.out.println("Buffer as a string");
System.out.println(f.toString());
System.out.println("Into array");

char c[] = f.toCharArray();
for (int i=0; i<c.length; i++) {
System.out.print(c[i]);
}

System.out.println("\nTo a FileWriter()");
FileWriter f2 = new FileWriter("test.txt");
f.writeTo(f2);
f2.close();
System.out.println("Doing a reset");
f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}
}


BufferedReader


BufferedReaderimproves performance by buffering input. It has two constructors:


BufferedReader(ReaderinputStream)
BufferedReader(ReaderinputStream, intbufSize)

The first form creates a buffered character stream using a default buffer size. In the second,
the size of the buffer is passed inbufSize.

Free download pdf