I won’t say much nonsense, I will just post the code to you. The specific code is as follows:
/** * Download the file with the specified path and write it to the specified location * * @param dirName * @param fileName * @param urlStr * @return Return 0 means downloading is successful, return 1 means downloading error */ public int downloadFile(String dirName, String fileName, String urlStr) { OutputStream output = null; try { //Convert the path in the form of a string into a url URL url = new URL(urlStr); //After getting the url, you will start connecting to the network, thinking it is the specific code for connecting to the network //First, instantiate an HTTP connection object conn HttpURLConnection conn = (HttpURLConnection) (); //Define the request method as GET, and do not make mistakes in case of GET. ("GET"); //Define the request time, it is best not to exceed 10 seconds in ANDROID. Otherwise it will be recycled by the system. (6 * 1000); //After the request is successful, the server will return a response code. If it is a GET request, the response code returned by the server is 200, and the response code returned by the post request server is 206 (seemingly). if (() == 200) { //The return code is true //The data passed from the server is an input action. Define an input stream to get the data returned from the server InputStream input = (); File file = createFile(dirName + fileName); output = new FileOutputStream(file); //Read large files byte[] buffer = new byte[1024]; //Record the reading content int n = (buffer); //Write to file (buffer, 0, n); n = (buffer); } (); (); } } catch (MalformedURLException e) { (); } catch (Exception e) { (); } finally { try { (); ("success"); return 0; } catch (IOException e) { ("fail"); (); } } return 1; } /** * Create a file on the specified directory of the SD card * * @param fileName */ public File createFile(String fileName) { File file = new File(fileName); try { (); } catch (IOException e) { (); } return file; }
The above is the implementation code for downloading files to the specified directory by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!