Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

以 Java NIO 記憶體映射檔案實作多執行緒下載

Java NIO 的記憶體映射檔案(MappedByteBuffer)很適合拿來實作多執行緒下載。基本思路是:主執行緒先取得遠端檔案的總長度,切成若干等份,為每份開一條執行緒,各自把對應區段寫入本機檔案的相同偏移位置,最後合併成完整檔案。

以下以多執行緒下載 Tomcat 壓縮檔為例:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;

class Worker implements Runnable {
    private static int THREADS = 4;   // 多執行緒下載數量
    private int startIndex;           // 每條執行緒的起始位置
    private int length;               // 每條執行緒下載的長度
    private String localFile;         // 檔案保存位置
    InputStream in;                   // 遠端檔案的流

    private Worker(String urlFile, String localFile, int startIndex, int length) throws IOException {
        this.startIndex = startIndex;
        this.length = length;
        this.localFile = localFile;
        init(urlFile);
    }

    /** 主執行緒打開網路檔案,先分割為指定大小,再開啟多執行緒下載 */
    public Worker(String urlFile, String localFile) throws IOException {
        this.localFile = localFile;
        int contentLength = init(urlFile);
        int step = contentLength / THREADS;
        int index = 0;
        for (int i = 0; i < THREADS; i++) {
            if (i == 0) {
                this.startIndex = 0;
                this.length = step;
                new Thread(this).start();
            } else if (i == THREADS - 1) {
                Worker worker = new Worker(urlFile, localFile, index, contentLength - index);
                new Thread(worker).start();
            } else {
                Worker worker = new Worker(urlFile, localFile, index, step);
                new Thread(worker).start();
            }
            index = index + step;
        }
    }

    private int init(String urlFile) throws IOException {
        URL url = new URL(urlFile);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5 * 1000);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Accept-Language", "zh-CN");
        connection.setRequestProperty("Charset", "UTF-8");
        connection.setRequestProperty("Connection", "Keep-Alive");
        InputStream in = connection.getInputStream();
        this.in = in;
        return connection.getContentLength();
    }

    @Override
    public void run() {
        System.out.println(this);
        try {
            RandomAccessFile localRandomFile = new RandomAccessFile(localFile, "rw");
            MappedByteBuffer buffer = localRandomFile.getChannel().map(MapMode.READ_WRITE, startIndex, length);
            int i = 0;
            in.skip(startIndex);
            while (i < length) {
                buffer.put((byte) in.read());
                i++;
            }
            buffer.force();
            in.close();
            localRandomFile.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return "Worker [localFile=" + localFile + ", startIndex=" + startIndex + ", length=" + length + "]";
    }

    public static void main(String[] args) throws IOException {
        new Worker("https://mirrors.cnnic.cn/apache/tomcat/tomcat-7/v7.0.53/bin/apache-tomcat-7.0.53.zip", "tomcat.zip");
    }
}

關鍵在於用 RandomAccessFile 定位到各自的起始偏移,再以 map 取得該區段的 MappedByteBuffer,寫滿後呼叫 force() 落盤,最後比對下載完成的檔案是否與原檔一致即可驗證正確性。

Copyright © Linux教程網 All Rights Reserved