Java downloads images from URLs and saves them to a local device.

Source: Internet
Author: User

Import java. Io. fileoutputstream;
Import java. Io. inputstream;
Import java. Io. outputstream;
Import java.net. url;
Import java.net. urlconnection;
/**
* Use urlconnection to download a file or image and save it locally.
*
* @ Author laozizhu.com)
*/
Public class urlconnectiondownloader {
Public static void main (string [] ARGs) throws exception {
Download ("http://www.laozizhu.com/images/logo.gif", "laozizhu.com.gif ");
}
/**
* 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 ();
// 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 ();
}

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.