The ready and readLine usage of BufferedReader, and the Premature EOF exception, prematureeof
Some users use the BufferedReader class ready when reading data returned by the server:
1 while (reader. ready () {2 // execute the read operation, that is, readLine 3}
This method is often used, but the returned results are empty. Why? I checked the help document and checked it online, and summarized it as follows:
1. ready is used to check whether the stream is ready to be read. It is a non-blocking method, so it will return immediately. Because the server is not ready to be read, it will return immediately, therefore, all read results are null.
2. readLine is a blocking method. As long as the connection is not disconnected, it will wait until something is returned. When will it return null? It will only return null when it reads the end of the data stream.
From: http://blog.csdn.net/neusoftware_20063500/article/details/3723176
In fact, data delay and other problems often occur when reading network data.
You can use the ready function to check whether BufferedReader is ready.
While (! Reader. ready) {// blocking, wait for a while} while (reader. readLine ()! = Null) {// execute the operation}
When reader. readLine has been read, false is returned if you continue to perform the ready operation. Therefore, the following two sections of code may cause an endless loop:
1.
While (reader. readLine ()! = Null) {// execute the operation while (! Reader. ready) {// blocking, waiting for a while }}
2.
While (reader. readLine ()! = Null) {// execute the operation} while (! Reader. ready) {// blocking, waiting for a while}
Premature EOF
Java. io. IOException: Premature EOF exception is easily encountered when reading network stream data.
Premature EOF may occur in the following ways:
1. Before stream reaches EOF, stream has ended. (No EOF marker). Obviously, in this case, it is likely that the response times out, server processing errors, network problems, and firewalls.
2. EOF appeared too early. (EOF marker comes earlier before it shoud be .)
Currently, no effective solution is found. There are many reasons for this problem. Some are client problems, which can be eliminated by improving good code habits. For example, remember to close the stream and network connection. Before reading the network stream, you can test whether the stream is ready.
Call the readline () method in bufferedreader
If (file. canRead () to if (bread. ready () Try
Use of the readLine () method in Java iobufferedreader class
Because the readLine () method may throw an IOException, you need to add or not handle this exception and throw it to the previous layer.
Try {
While (input = br. readLine ())! = Null )){...}
} Catch (IOException e ){}
Public Object read () throws IOException {
While (input = br. readLine ())! = Null )){...}
}