Java downloads files from the network URL

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/xb12369/article/details/40543649

/*** Download files from the Web URL *@paramUrlstr *@paramFileName *@paramSavepath *@throwsIOException*/     Public Static voidDownloadfromurl (String urlstr,string filename,string Savepath)throwsioexception{URL url=NewURL (URLSTR); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); //set the timeout time to 3 secondsConn.setconnecttimeout (3*1000); //prevents the masking program from crawling and returns a 403 errorConn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 5.0; Windows NT; Digext) "); //Get input streamInputStream InputStream =Conn.getinputstream (); //get your own array        byte[] GetData =Readinputstream (InputStream); //File Save locationFile Savedir =NewFile (Savepath); if(!savedir.exists ())        {Savedir.mkdir (); } File File=NewFile (savedir+file.separator+fileName); FileOutputStream Fos=Newfileoutputstream (file);         Fos.write (GetData); if(fos!=NULL) {fos.close (); }        if(inputstream!=NULL) {inputstream.close (); } System.out.println ("Info:" +url+ "Download Success"); }    /*** Get the byte array from the input stream *@paramInputStream *@return     * @throwsIOException*/     Public Static  byte[] Readinputstream (InputStream inputstream)throwsIOException {byte[] buffer =New byte[1024]; intLen = 0; Bytearrayoutputstream Bos=NewBytearrayoutputstream ();  while(len = inputstream.read (buffer))! =-1) {bos.write (buffer,0, Len);          } bos.close (); returnBos.tobytearray (); }       Public Static voidMain (string[] args) {Try{Downloadfromurl ("Http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",                    "Baidu. jpg", "d:/resource/images/diaodiao/country/"); }Catch(Exception e) {//Todo:handle Exception        }    }

Java downloads files from the network URL

Related Article

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.