从指定的URL下载文件并将其保存到指定的目录

/**
 * Download the file from the specified URL and save it to the specified directory
 * 
 * @param url Requested URL
 * @param filePath The directory where the file will be saved
 * @param method GET or POST
 * @param fileName
 * @return
 */

public static File saveUrlAs(String url, String filePath, String method, String fileName) {
    // Create different folder directories
    File file = new File(filePath);
    // Determine whether the folder exists
    if (!file.exists()) {
        // If the folder does not exist, a new folder is created
        file.mkdirs();
    }
    FileOutputStream fileOut = null;
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    try {
        // Establish link
        URL httpUrl = new URL(url);
        conn = (HttpURLConnection) httpUrl.openConnection();
        // Submit the form in post mode. The default mode is get
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        // Cache cannot be used in post mode
        conn.setUseCaches(false);
        // Connect to the specified resource
        conn.connect();
        // Get network input stream
        inputStream = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        // Judge whether the saving path of the file ends with /
        if (!filePath.endsWith("/")) {
            filePath += "/";
        }
        // Write to file (note that the file name must be added after the file saving path)
        fileOut = new FileOutputStream(filePath + fileName);
        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();
    }

    return file;

}

你可能感兴趣的:(从指定的URL下载文件并将其保存到指定的目录)