Save files in the Network

Source: Internet
Author: User
Package cn.cctv.net; import Java. io. bytearrayoutputstream; import Java. io. file; import Java. io. fileoutputstream; import Java. io. inputstream; import java.net. httpurlconnection; import java.net. URL; public class imagerequest {/*** @ Param ARGs */public static void main (string [] ARGs) throws exception {// new a URL object url = new URL ("http://img.hexun.com/2011-06-21/130726386.jpg"); // open the link httpurlco Nnection conn = (httpurlconnection) URL. openconnection (); // set the Request Method to "get" Conn. setrequestmethod ("get"); // timeout response time is 5 seconds Conn. setconnecttimeout (5*1000); // you can use the input stream to obtain the image data. inputstream instream = Conn. getinputstream (); // obtain the binary data of the image, which is encapsulated in binary format to obtain the data. It has the versatility of byte [] DATA = readinputstream (instream); // a new file object is used to save the image, by default, the current project root directory file imagefile = new file ("beautygirl.jpg") is saved; // The output stream fileoutputstream outstream = new fileo is created. Utputstream (imagefile); // write data outstream. write (data); // close the output stream outstream. close ();} public static byte [] readinputstream (inputstream instream) throws exception {bytearrayoutputstream outstream = new bytearrayoutputstream (); // create a buffer string byte [] buffer = new byte [1024]; // The length of the string to be read each time. If it is-1, int Len = 0 indicates that all data has been read; // use an input stream to read data from the buffer while (LEN = instream. read (buffer ))! =-1) {// use the output stream to write data to the buffer. The intermediate parameter indicates the position from which the read starts, and Len indicates the length of the read outstream. write (buffer, 0, Len);} // close the instream of the input stream. close (); // write the data in outstream to the memory return outstream. tobytearray ();}}

 

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.