/** * Download files from the network URL * @param urlstr * @param fileName * @param savepath * @throws IOException */public static void Downloadfromurl (String urlstr,string filename,string savepath) throws ioexception{UR L url = new URL (urlstr); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Set the timeout time to 3 seconds conn.setconnecttimeout (3*1000); Prevents the masking program from crawling and returns 403 error Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 5.0; Windows NT; Digext) "); Get input stream InputStream InputStream = Conn.getinputstream (); Get own array byte[] GetData = Readinputstream (InputStream); File save location Files Savedir = new file (Savepath); if (!savedir.exists ()) {Savedir.mkdir (); } File File = new file (savedir+file.separator+filename); FileOutputStream fos = new FileOutputStream (file); Fos.write (getData); if (fos!=null) {fos.close (); } if (Inputstream!=null) {inputstream.close (); } System.out.println ("Info:" +url+ "Download Success"); /** * Gets the byte array from the input stream * @param inputstream * @return * @throws IOException */publi C Static byte[] Readinputstream (InputStream inputstream) throws IOException {byte[] buffer = new byte[1024]; int len = 0; Bytearrayoutputstream BOS = new Bytearrayoutputstream (); while (len = inputstream.read (buffer))! =-1) {bos.write (buffer, 0, Len); } bos.close (); return Bos.tobytearray (); } public static void Main (string[] args) {try{Downloadfromurl ("http://101.95.48.97:8005/r Es/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