Download online images to the local java tool class, and download images to the java tool class

Source: Internet
Author: User

Download the network segment to the local java tool class, and download the image java tool class

Package com. swift; import java. io. file; import java. io. fileOutputStream; import java. io. inputStream; import java.net. httpURLConnection; import java.net. URL; public class DownloadPicUtil {public static final int DEF_CONN_TIMEOUT = 30000; public static final int DEF_READ_TIMEOUT = 30000; public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) appleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547. 66 Safari/537.36 "; public static void downloadPic (String strUrl, String savePath) throws Exception {HttpURLConnection conn = null; URL url = new URL (strUrl); conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setRequestProperty ("User-agent", userAgent); conn. setUseCaches (false); conn. setConnectTimeout (DEF_CONN_TIMEOUT); conn. setReadTimeout (DEF_READ_TIMEOUT); conn. s EtInstanceFollowRedirects (false); conn. connect (); InputStream is = conn. getInputStream (); // connect to get the input stream content File = new file (savePath); if (! File. exists () {// If the saved Folder does not exist, a file is created. mkdirs ();} FileOutputStream fos = new FileOutputStream (new File (savePath, strUrl. substring (strUrl. lastIndexOf ("/") + 1); // obtain the image name int intRead = 0 in the URL; byte [] buf = new byte [1024*2]; // generate a 2 K container for receiving the image byte stream while (intRead = is. read (buf ))! =-1) {fos. write (buf, 0, intRead); // The file output streams to the specified path file fos. flush ();} fos. close (); // close the output stream if (conn! = Null) {conn. disconnect (); // close the connection }}}

 

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.