使用Hutool下載文件詳解

在日常開發中,下載文件是很常見的需求。Hutool是一款優秀的Java工具庫,它提供了方便簡潔的文件下載方法。

一、下載文件流程

使用Hutool下載文件的流程如下:


    File file = new File("D://test//test.xlsx");
    HttpUtil.downloadFile("http://example.com/test.xlsx", file);

第一步:定義下載文件的存儲路徑及文件名;

第二步:使用HttpUtil.downloadFile()方法下載文件;

上述代碼簡單易懂,體現了Hutool的易用性。

二、下載圖片

有時候我們需要從某些網站下載圖片,下面是使用Hutool下載圖片的方法:


    File file = new File("D://test//test.jpg");
    HttpUtil.downloadFile("http://example.com/test.jpg", file);

downloadFile()方法同樣適用於圖片下載。使用Hutool下載圖片和文件一樣簡單。

三、下載大文件

如果需要下載大文件,我們可以使用get方法下載。如下所示,我們可以設置連接超時時間和讀取超時時間:


    HttpResponse response = HttpUtil.createGet(url)
            .setConnectionTimeout(20000)
            .setReadTimeout(120000)
            .timeout(3600000)
            .execute();
    InputStream inputStream = response.bodyStream();
    OutputStream out = new FileOutputStream("D://test//test.mp4");
    IoUtil.copy(inputStream, out, IoUtil.DEFAULT_BUFFER_SIZE);
    response.close();

在下載大文件時,我們不僅僅需要設置超時時間,還需要使用較大的buffer_size,以便能夠快速讀寫。

四、斷點續傳

如果下載文件時,由於網絡等原因導致下載失敗,可以使用斷點續傳的方法。


    String url = "http://example.com/test.xlsx";
    File file = new File("D://test//test.xlsx");
    long fileLen = file.length();
    HttpRequest request = HttpUtil.createGet(url).header("User-Agent", HttpUtil.userAgent).header("Accept-Encoding", "identity");
    HttpConnection connection = HttpUtil.getConnection(request.getUrl(), Method.GET, true);
    if (fileLen > 0) {
        connection.header("Range", "bytes=" + fileLen + "-");
    }
    HttpResponse response = HttpUtil.execute(request.method(connection));
    if (response.getStatus() == HttpStatus.HTTP_NOT_MODIFIED) {
        System.out.println("文件未修改");
    } else if (response.getStatus() != HttpStatus.HTTP_PARTIAL_CONTENT) {
        throw new HttpStatusException(response.getStatus(), response.getContent());
    }
    RandomAccessFile out = new RandomAccessFile(file, "rw");
    if (fileLen > 0) {
        out.seek(fileLen);
    }
    InputStream in = response.bodyStream();
    int len;
    byte[] buff = new byte[4096];
    while ((len = in.read(buff)) != -1) {
        out.write(buff, 0, len);
    }
    response.close();
    out.close();

上面是使用斷點續傳的完整代碼,其中設置了請求頭Range,該請求頭用於請求部分資源。設置Range後,服務端僅返回請求範圍內的數據,這樣可以使用多次請求的方式實現斷點下載。

五、自動重試

下載文件時,有時候會由於網絡波動等原因導致下載失敗。這樣我們需要在下載失敗時,自動重試下載,以確保文件下載完成。


    RetryUtil.executeBySimple(retryCount, retryTimeIntervalInMillis, new Callable(){
        HttpResponse response = HttpUtil.createGet(url)
                .setConnectionTimeout(20000)
                .setReadTimeout(120000)
                .execute();
        InputStream inputStream = response.bodyStream();
        OutputStream out = new FileOutputStream("D://test//test.mp4");
        IoUtil.copy(inputStream, out, IoUtil.DEFAULT_BUFFER_SIZE);
        response.close();
        return null;
    });

RetryUtil.executeBySimple()方法可以實現簡單的重試功能,可以在請求失敗之後進行自動重試。

六、總結

本文對使用Hutool下載文件做了詳細的闡述,從下載文件的流程、下載圖片、下載大文件、斷點續傳到自動重試,一一講解。Hutool下載文件的方法簡單易用,能夠滿足日常開發中的大部分需求。

原創文章,作者:HRGMN,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/333619.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
HRGMN的頭像HRGMN
上一篇 2025-02-01 13:34
下一篇 2025-02-01 13:34

相關推薦

發表回復

登錄後才能評論