I have such code to read a text file using BufferedReader:
BufferedReader reader=null;
try {
reader = new BufferedReader(new FileReader("file1.txt"));
while (reader.ready()) {
final String line = reader.readLine();
System.out.println("<"+line+">");
} catch (..)
{
...
}
It works correctly but Findbugs reports a warning:
NP_DEREFERENCE_OF_READLINE_VALUE : The result of invoking readLine() is dereferenced without checking to see if the result is null. If there are no more lines of text to read, readLine() will return null and dereferencing that will generate a null pointer exception.
When I change FileReader to StringReader, i.e.
BufferedReader reader=null;
try {
reader = new BufferedReader(new StringReader("ABCD"));
while (reader.ready()) {
final String line = reader.readLine();
System.out.println("<"+line+">");
} catch (..)
{
...
}
the readLine method returns null while the ready method always returns true - indeed this is an infinite loop.
This seems that the readLine may return null even if ready returns true. But why does the behavior differ for different Readers?
UPDATE:
I do know the normal way to read a text file (just like Peter and Ali illustrated). but I read that piece of code from my colleague and realized that I don't know the ready method. Then I read the JavaDoc, but don't understand block. Then I did a test and posted this question. So, the better way to put this question might be:
When will the input be blocking? How to use the ready method (or why not to use it)? Why do those 2 Readers (FileReader and StringReader) behave differently with regards to the ready method?