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