[ACCEPTED]-Does BufferedReader.ready() method ensure that readLine() method does not return NULL?-file-io
The ready method tells us if the Stream 12 is ready to be read.
Imagine your stream 11 is reading data from a network socket. In 10 this case, the stream may not have ended, because 9 the socket has not been closed, yet it may 8 not be ready for the next chunk of data, because 7 the other end of the socket has not pushed 6 any more data.
In the above scenario, we 5 cannot read any more data until the remote 4 end pushes it, so we have to wait for the 3 data to become available, or for the socket 2 to be closed. The ready() method tells us 1 when the data is available.
The Reader.ready() and InputStream.available() rarely 3 work as you might like, and I don't suggest 2 you use them. To read a file you should 1 use
String line;
while ((line = reader.readLine()) != null)
System.out.println("<"+line+">");
Here's what the Javadocs have to say:
Tells 17 whether this stream is ready to be read. A 16 buffered character stream is ready if the 15 buffer is not empty, or if the underlying 14 character stream is ready.
So a BufferedReader 13 is considered ready simply if the underlying stream is also 12 ready. Since BufferedReader is a wrapper, this 11 underlying stream could be any Reader implementation; hence 10 the semantics of ready()
are those declared on 9 the interface:
Returns true if the next read() is 8 guaranteed not to block for input, false 7 otherwise. Note that returning false does 6 not guarantee that the next read will block.
So 5 you only really get timing guarantees, i.e. that 4 read()
will not block. The result of calling 3 ready()
tells you absolutely nothing about the 2 content you'll get back from a read()
call, and so cannot 1 be used to elide a null check.
Look at the API for ready.
What you're doing is wrong. ready()
only 3 tells you if the stream is readable and 2 valid. Read the comment under return on 1 that link as well.
What you want to do is:
String thisLine;
//Loop across the arguments
for (int i=0; i < args.length; i++) {
//Open the file for reading
try {
BufferedReader br = new BufferedReader(new FileReader(args[i]));
while ((thisLine = br.readLine()) != null) { // while loop begins here
System.out.println(thisLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error: " + e);
}
} // end for
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.