When I was working on a project yesterday, I used the knowledge of downloading files from the server and saving them locally. I have never touched it before. I worked on it for a day yesterday, and this small function was realized. The following is a brief description of the realization process;
1. Basic knowledge
When we want to download a resource on the website, we will get a url, which is a description of the resource located by the server. The download process has the following steps:
(1) The client initiates a url request to obtain the connection object.
(2) The server parses the url and returns the specified resource as an input stream to the client.
(3) Create a storage directory and a saved file name.
(4) Write data is output.
(5) Close the input stream and output stream.
2. How to implement the code
/** * @Function to download temporary material interface * @param filePath The directory where the file will be saved * @param method request method, including POST and GET * @param url the requested 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); //Check 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 { // create link URL httpUrl=new URL(url); conn=(HttpURLConnection) httpUrl.openConnection(); //Submit the form in Post mode, default get mode conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(true); // post method cannot use cache conn.setUseCaches(false); //connect to the specified resource conn.connect(); //get network input stream inputStream=conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(inputStream); / / Determine whether the save path of the file ends with / if (!filePath.endsWith("/")) { filePath += "/"; } //Write to the file (note that the file save path must be followed by the name of the file) fileOut = new FileOutputStream(filePath+"123.png"); BufferedOutputStream bos = new BufferedOutputStream(fileOut); byte[] buf = new byte[4096]; int length = bis.read(buf); //save document 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 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); }