Java using InputStream Notes

Source: Internet
Author: User

When we want to download resources from the network, we use a similar approach to get InputStream instances:

New URL ("Http://www.XXXX.XXX"= Connection.getinputstream ();

But this InputStream instance has some differences from the InputStream instance where we read the file.

Let's talk. Read files using InputStream

New FileInputStream (new File ("XXX"));

We can get the number of bytes in the file by Inputstream.available ()

Using Inputstream.read (byte[] b, int off, int len) to attempt to read Len bytes to byte array b, if the bytes in the input stream are greater than Len, read the Len arrays, if the number of bytes in the input stream is less than Len, Reads the number of bytes remaining and eventually returns the bytes read, which returns 1 when the end of the file is read.

However, for the input stream obtained by the Connection.getinputstream () method, the above two methods do not apply:

The number of bytes obtained by the available () method differs greatly from the total number of bytes in the input stream, and is obtained using the connection.getcontentlength () method if you want to obtain the specific number of bytes for a network resource.

While the Inputstream.read (byte[] b, int off, int len) method, when the byte array b length and Len is very large, there will be read incomplete, that is, the number of bytes in the input stream is greater than Len, But the number of bytes read is still less than Len . So this situation must be read by using the while loop, with the return value to determine the number of bytes read (preferably when reading a file)

 while (length = inputstream.read (data, 0, data.length))! =-1) {        XXXX}

Java using InputStream Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.