Yesterday in a project, the use of downloading files from the server and save to the local knowledge, has not been contacted, yesterday made a day, this small function realized, the following simple to say the implementation process;
1. Basic knowledge when we want to download a resource on the site, we get a URL, which is a description of the server location resource, the download process has the following steps: (1) The client initiates a URL request to get the connection object. (2) The server resolves the URL, and returns the specified resource to the client with an input stream. (3) Create a stored directory and a saved file name. (4) Output the write data. (5) Close the input stream and the output stream. 2. Ways to implement Code
/** * @ feature Download temporary footage interface * @param filePath file will be saved directory * @param method request methods, including post and get * @param URL Request path * @return */ public static File Saveurlas (String url,string filepath,string method) {//system.out.println ("fileName---->" + FilePath); Create a different folder directory file File=new file (FilePath); Determine if the folder exists if (!file.exists ()) {//If the folder does not exist, create a new folder File.mkdirs (); } FileOutputStream fileout = null; HttpURLConnection conn = null; InputStream inputstream = null; try {//Establish link URL httpurl=new url (url); Conn= (HttpURLConnection) httpurl.openconnection (); Submit form by post, default get Mode Conn.setrequestmethod (method); Conn.setdoinput (TRUE); Conn.setdooutput (TRUE); Post mode cannot use cache conn.setusecaches (false); Connect the specified resource Conn.connect (); Get the network input stream Inputstream=conn.getinputstream (); BuffEredinputstream bis = new Bufferedinputstream (InputStream); Determines whether the file's save path is followed by/ending if (!filepath.endswith ("/")) {FilePath + = "/"; }//write to the file (note that the file name must be appended to the path to save files) Fileout = new FileOutputStream (filepath+ "123.png"); Bufferedoutputstream BOS = new Bufferedoutputstream (fileout); byte[] buf = new byte[4096]; int length = Bis.read (BUF); Save file while (length! =-1) {bos.write (buf, 0, length); Length = Bis.read (BUF); } bos.close (); Bis.close (); Conn.disconnect (); } catch (Exception e) {e.printstacktrace (); System.out.println ("Throw an exception!! "); } return file; }
3. Code test Class (main function)
/** * @param args * /public static void main (string[] args) { String photourl = "https:// Ss0.bdstatic.com/5av1bjqh_q23odcf/static/superman/img/logo/bd_logo1_31bdc765.png "; String fileName = photourl.substring (Photourl.lastindexof ("/")); System.out.println ("fileName---->" +filename); String FilePath = "D:"; File File = Saveurlas (Photourl, FilePath + fileName, "GET"); System.out.println ("Run ok!/n<br>get URL File" + file); }
Java downloads files from the server and saves them locally