Java downloads the image file from the remote http address to the local device-automatically processes whether the image is compressed by gzip on the server.

Source: Internet
Author: User

Java downloads the image file from the remote http address to the local device-automatically processes whether the image is compressed by gzip on the server.

Directly run the Code:

/**
* Download an object to a local device.
*
* @ Param urlString
* Address of the downloaded file
* @ Param filename
* Local file name
* @ Throws Exception
* Various exceptions
*/
Public static void download (String urlString, String filename)
Throws Exception {
// Construct a URL
URL url = new URL (urlString );
// Open the connection
URLConnection con = url. openConnection ();
// Input stream
InputStream is = con. getInputStream ();

String code = con. getHeaderField ("Content-Encoding ");
System. out. println ("cdoe:" + code );
 
 
If (null! = Code) & code. equals ("gzip "))
{
GZIPInputStream gis = new GZIPInputStream (is );

// 1 k Data Buffer
Byte [] bs = new byte [1024];
// Read Data Length
Int len;
// Output file stream
OutputStream OS = new FileOutputStream (filename );
// Start reading
While (len = gis. read (bs ))! =-1 ){
OS. write (bs, 0, len );
}
// Close all links
Gis. close ();
OS. close ();
Is. close ();

}
Else
{

// 1 k Data Buffer
Byte [] bs = new byte [1024];
// Read Data Length
Int len;
// Output file stream
OutputStream OS = new FileOutputStream (filename );
// Start reading
While (len = is. read (bs ))! =-1 ){
OS. write (bs, 0, len );
}
// Close all links
OS. close ();
Is. close ();
}

}

Related Article

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.