If no mark is used in a network stream, you do not know whether the stream ends. However, when reading the network stream, we can know how many bytes can be read this time by using inputstream. available (), but it must be called at least once after Read (), that is, the available method must be called after Read, otherwise it will only get zero value. Note: here the stream in network transmission is like this, but the file stream is not like this. You can use available to determine the number of bytes of content that can be read.
Available () of inputstream: return the number of bytes that can be read by the input stream without being blocked. The key to the difference between a network stream and a file stream is whether the word "blocked". When a network socket stream is read, The read () method will be blocked if there is no content, therefore, the available of the input stream initialized from the socket is zero. Therefore, you need to read the field and use it again. In this way, the number of available bytes is equal to available + 1. However, when reading a file, read () is generally not blocked, because the number of available bytes of the file stream
Available = file. Length (), and the Content Length of the file is known when the file object is created.
Number of bytes available for the network socket input streamCodeAs shown in:
// Save the received data to the byte array <br/> int firstchar = inputstream. read (); <br/> int length = inputstream. available (); <br/> byte [] array = new byte [Length + 1]; <br/> array [0] = (byte) firstchar; <br/> inputstream. read (array, 1, length );
The code shows the number of available bytes of a file stream:
fileinputstream Fi = new fileinputstream ("E: /tmp "); <br/> // read all the file content cyclically. You can directly use <br/> while (Fi. available ()> 0) {<br/> system. out. println (byte) Fi. read (); // encode the output content, not the character encoding. It may be negative, such as binary image files <br/>}< br/> fi. close ();