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 ();
}