Name: bk70084 Date: 11/03/97
The BufferedReader will not read as many characters as were requested if the buffer is
emptied during a read(). For the example below, the buffer size is 10 characters, but
only 8 characters at a time are read from the stream. The result is, on the first read()
8 characters are read, but on the second read() only 2 characters are read because the
buffer is empty.
//================= Test.java ======================
import java.io.*;
public class Test
{
public static void main(String args[]) throws IOException
{
Reader stream=new BufferedReader(new FileReader("TEST.TXT"), 10);
char cbuf[]=new char[8];
for (int j=0; j<10; j++)
{
int n=stream.read(cbuf);
System.out.println("Have read "+n+" characters: "+cbuf);
}
System.out.println("Press any key");
System.in.read();
}
}
This is the code of BufferedReader.read(char[], int, int). I see a problem if I want to read more characters than the
buffer capacity:
public int read(char cbuf[], int off, int len) throws IOException {
synchronized (lock) {
ensureOpen();
if (nextChar >= nChars) {
if (len >= cb.length && markedChar <= UNMARKED) {
return in.read(cbuf, off, len);
}
fill();
}
if (nextChar >= nChars)
return -1;
/* ==============================================
* PROBLEM AHEAD!!!!
* What about if I want to read 20 characters but
* only 10 characters are left in the buffer?????
* ============================================== */
int n = Math.min(len, nChars - nextChar);
System.arraycopy(cb, nextChar,
cbuf, off, n);
nextChar += n;
return n;
}
}
(Review ID: 15048)
======================================================================