Java通過URL下載文件到本地

在Java中,通過URL下載文件到本地非常常見。 下面將介紹如何使用Java實現從URL下載文件到本地的操作。

一、建立URL連接並打開連接


public static void downloadFileFromURL(String fileURL, String saveDir) throws IOException {
    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setRequestMethod("GET");
    int responseCode = httpConn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        //連接成功
    } else {
        //連接失敗
    }
}

在第一步中,我們通過URL對象建立與遠程伺服器的連接,並向該伺服器發起一個HTTP GET請求,並且我們通過getResopnseCode()方法獲取伺服器的響應狀態碼。

二、從連接中獲取輸入流並從輸入流中讀取數據


public static void downloadFileFromURL(String fileURL, String saveDir) throws IOException {
    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setRequestMethod("GET");
    int responseCode = httpConn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        // 獲取文件名
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        String contentType = httpConn.getContentType();
        int contentLength = httpConn.getContentLength();
        if (disposition != null) {
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                fileName = disposition.substring(index + 10, disposition.length() - 1);
            }
        } else {
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
        }

        // 輸出文件信息
        System.out.println("Content-Type = " + contentType);
        System.out.println("Content-Disposition = " + disposition);
        System.out.println("Content-Length = " + contentLength);
        System.out.println("fileName = " + fileName);

        // 開始下載文件
        InputStream inputStream = httpConn.getInputStream();
        String saveFilePath = saveDir + File.separator + fileName;
        FileOutputStream outputStream = new FileOutputStream(saveFilePath);
        int bytesRead = -1;
        byte[] buffer = new byte[4096];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
        System.out.println("文件已經下載到 " + saveFilePath + ".");
    } else {
        System.out.println("伺服器返迴響應碼 " + responseCode);
    }
}

在第二步中,我們通過輸入流從連接中讀取遠程伺服器傳輸的數據。

三、將輸入流寫入本地文件


public static void downloadFileFromURL(String fileURL, String saveDir) throws IOException {
    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setRequestMethod("GET");
    int responseCode = httpConn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        // 獲取文件名
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        String contentType = httpConn.getContentType();
        int contentLength = httpConn.getContentLength();
        if (disposition != null) {
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                fileName = disposition.substring(index + 10, disposition.length() - 1);
            }
        } else {
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
        }

        // 輸出文件信息
        System.out.println("Content-Type = " + contentType);
        System.out.println("Content-Disposition = " + disposition);
        System.out.println("Content-Length = " + contentLength);
        System.out.println("fileName = " + fileName);

        // 開始下載文件
        InputStream inputStream = httpConn.getInputStream();
        String saveFilePath = saveDir + File.separator + fileName;
        FileOutputStream outputStream = new FileOutputStream(saveFilePath);
        int bytesRead = -1;
        byte[] buffer = new byte[4096];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
        System.out.println("文件已經下載到 " + saveFilePath + ".");
    } else {
        System.out.println("伺服器返迴響應碼 " + responseCode);
    }
}

在第三步中,我們創建一個FileStream對象並將輸入流中的數據寫入該對象。 最後,將FileStream中的數據寫入本地文件。

四、異常處理

在對下載文件進行異常處理時,我們需要考慮多種情況:

  • 連接失敗
  • 文件名提取失敗
  • 無法獲取響應狀態碼。

為了更好地處理這些異常情況,我們需要將下載文件的實現代碼封裝成一個方法,並拋出異常。

五、完整代碼示例


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadFileUtil {

    public static void downloadFileFromURL(String fileURL, String saveDir) throws IOException {

        // 建立URL連接並打開連接
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("GET");

        // 從連接中獲取輸入流並從輸入流中讀取數據
        int responseCode = httpConn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
            int contentLength = httpConn.getContentLength();

            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10, disposition.length() - 1);
                }
            } else {
                // extracts file name from URL
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
            }

            // 輸出文件信息
            System.out.println("Content-Type = " + contentType);
            System.out.println("Content-Disposition = " + disposition);
            System.out.println("Content-Length = " + contentLength);
            System.out.println("fileName = " + fileName);

            // 將輸入流寫入本地文件
            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = saveDir + File.separator + fileName;
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);
            int bytesRead = -1;
            byte[] buffer = new byte[4096];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();
            System.out.println("文件已經下載到 " + saveFilePath + ".");
        } else {
            System.out.println("伺服器返迴響應碼 " + responseCode);
        }
    }
}

六、總結

在Java中實現從URL下載文件到本地非常常見。到現在,您應該已經掌握了如何使用Java對文件進行下載,並成功下載文件到本地。儘管這個過程看起來很簡單,但是由於許多伺服器強制使用HTTPS,所以我們需要使用Java的加密通信。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/187644.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-28 06:24
下一篇 2024-11-28 06:24

相關推薦

發表回復

登錄後才能評論