1. About Inputstream.read ()
When reading data from a data stream, it is easy to use the Inputstream.read () method for diagrams. This method is to read one byte at a time from the stream and is very inefficient. A better approach is to read multiple bytes at a time using Inputstream.read (byte[] b) or Inputstream.read (byte[] B,int Off,int len) methods.
2. Available () method for the InputStream class
To read more than one byte at a time, the Inputstream.available () method is often used, which allows you to know how many bytes in the data stream can be read before the read and write operation. It is important to note that if this method is used in the
When the data is read by the file, it is generally not a problem, but if it is used for network operation, it often encounters some trouble. For example, the socket communication, the Fangmingming sent 1000 bytes, but its own program calls available () method only get 900, or 100, or even 0, feel a bit inexplicable, how can not find the reason. In fact, this is because network traffic is often intermittent, a string of bytes are often divided into several batches to send. The local program call available () method sometimes gets 0, which may be that the other party has not responded, or it may have responded, but the data has not been delivered locally. The other side sends 1000 bytes to you, perhaps into 3 batches, which you will call 3 times available () method to get the total number of data.
If you write code like this:
int count = In.available ();
Byte[] B = new Byte[count];
In.read (b);
In the network operation is often error, because when you call the available () method, the data sent to the send may not have arrived, you get the count is 0.
Need to change to this:
int count = 0;
while (count = = 0) {
Count = In.available ();
}
Byte[] B = new Byte[count];
In.read (b);
3. With regard to Inputstream.read (byte[] b) and Inputstream.read (byte[] b,int Off,int len) Both methods are used to read multiple bytes from the stream, and experienced programmers will find that these two methods are often You cannot read the number of bytes that you want to read. For example, the first method, programmers often want the program to read B.length bytes, and the reality is that the system is often not read so much. A closer look at the Java API description reveals that this method does not guarantee that you can read so many bytes, it can only guarantee to read so many bytes (at least 1). Therefore, if you want a program to read count bytes, it is best to use the following code:
Byte[] B = new Byte[count];
int readcount = 0; The number of bytes that have been successfully read
while (Readcount < count) {
Readcount + = in.read (bytes, readcount, count-readcount);
}
Use this code to ensure that count bytes are read unless an IO exception is encountered halfway through or at the end of the data stream (eofexception)
Java inputstream read data problem (GO)