Download the image file for "Http://www.baidu.com/img/bd_logo1.png" by code
package guwen;import java.io.bytearrayoutputstream;import java.io.file;import java.io.fileoutputstream;import java.io.ioexception;import java.io.inputstream;import java.net.httpurlconnection;import java.net.url;public class downurl { public static void main (String[] args) throws IOException { String link = "Http://www.baidu.com/img/bd_logo1.png" ; // new a URL object url url = new url (link); // Open link HttpURLConnection conn = (HttpURLConnection) url.openconnection (); // Set request mode is "GET" conn.setrEquestmethod ("GET"); // timeout response time is 5 seconds conn.setconnecttimeout (5 * 1000); //can learn the types of resources through contentType String Contenttype = conn.getcontenttype (); System.out.println ("contenttype: " +contenttype); // Get file data from an input stream InputStream inStream = Conn.getinputstream (); // Gets the binary data of the resource, obtains the data in binary package, has the universality ByteArrayOutputStream outStream = new Bytearrayoutputstream (); // Create a buffer string byte[] buffer = new byte[1024]; // the string length of each read, if 1, all reads are complete int len = 0; // use an input stream to read the data out of the buffer while (len = instream.read (buffer)) != -1) { // writes the data to buffer with the output stream, and the middle parameter represents where to start reading, and Len represents the length of the read outstream.write (Buffer, 0, len); } // Close input Stream instream.close (); // writes the data in the OutStream to memory byte[] data = outstream.tobytearray (); // new a file object is used to save files, or incoming databases, etc. String savepath = "D://file"; file file = new file (Savepath); string parentstr = File.getparent (); file parentflie = new File (PARENTSTR); if (!parentflie.exists ()) { parentflie.mkdirs (); } // Create an output stream fileoutputstream fileoutstream = new fileoutputstream (file); // Writing Data Fileoutstream.write (data); // closing the output stream Fileoutstream.close (); }}
After running. The image will be downloaded to the computer's C drive file.
The resource file for the Java download URL