"A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached". Folks! Pay attention on that "null"! Wanna arguments? Have a real-life examples:
1. HOW-TO-DO: correct way to read input data
BufferedReader reader; //... String line; while ((line = reader.readLine()) != null) { //do something }Major point in this example is a null-checking, i.e., we should not only read data but also check if the wrapped stream hasn't been closed.
2. HOW-NOT-TO-DO: incorrect way to parse some text from read input data
BufferedReader reader; //... String line; while (true) { line = reader.readLine()); if ((line == null)) || !line.isEmpty()) { // All input data has been read so let's analyze it analyzeBunchOfData(); } }
What's wrong here? That old ugly null returned by BufferedReader. Here we assume that if nothing (null) has been read - than some bunch of input data has come. But it is no so! Again, if BufferedReader returns null - it means that internal stream has been closed, that, in turn, in most cases means that input resource has been closed, for example, network connection has been closed on the other side.
The moral
Be accurate when you work with low-level input/output operations. At least.
No comments:
Post a Comment