Actually, this code shows something very interesting:
To be a little more descriptive, assume that "check.txt" contains a second line, say "Wooorld". Then the result will be the same.
The -1 indicates that the file has been read completely. This is because
1. BufferedReader.readLine() usually reads internally more than just one line 2. The FileWriter instance points internally to the last character that has been read. And reading through the BufferedReader also modifies this position.
So the instances fr and br doesn't read independently from each other.
In this code FileReader is wrapped by BufferedReader - BufferedReader reads from FileReader, and FileReader reads from file. At first read request BufferedReader reads from FileReader a portion of stream (file) into it's buffer in the memory. If file is smaller than the buffer size (probably your file is smaller), then whole file is read at once into the buffer. So, now the whole file was just read from FileReader, and then each call to it's read method returns -1 (end of file). But BufferedReader has it's own file position pointer (that points to the buffer), and each call to the BufferedReader's read method reads next portion of file from buffer.
posted 12 years ago
each call to the BufferedReader's read method reads next portion of file from buffer
In fact it's a combination of reading from buffer and file, whereby the BufferedReader's position pointer is harmless. It's the FileReader's position pointer that can cause confusion. Look: will print
because the second fr.read has positioned fr's position pointer after the second line feed.
But wouldn't Shashank's example give stuff for a nice exam question ? [ July 06, 2008: Message edited by: Ralph Jaus ]