1. 程式人生 > >RandomAccessFile實現多執行緒檔案複製

RandomAccessFile實現多執行緒檔案複製

RandomAccessFile

RandomAccessFile是Java體系中輸入/輸出流體系中功能最豐富的類之一,擁有強大的API,既支援檔案的讀,又支援檔案的寫;支援“隨機訪問”的方式,即程式可以直接跳轉到檔案的任意地方來讀寫資料。利用這個特性可以實現檔案的多執行緒複製,將大檔案分成若干段,每一段啟動一個執行緒複製該段的檔案,大大提高了效率。

程式碼實現


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

class CopyFileThread extends Thread{
    private
RandomAccessFile in; private RandomAccessFile out; private long start; private long end; /** * * @param in 原始檔地址 * @param out 目標檔案地址 * @param start 分段複製的開始位置 * @param end 分段複製的結束位置 */ public CopyFileThread(String in, String out, long start, long
end){ this.start = start; this.end = end; try { this.in = new RandomAccessFile(in, "rw"); this.out = new RandomAccessFile(out, "rw"); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void run(){ try
{ in.seek(start); out.seek(start); int hasRead = 0; byte[] buff = new byte[1024*1024]; while(start<end && (hasRead = in.read(buff)) != -1){ start += hasRead; out.write(buff, 0, hasRead); } } catch (IOException e) { e.printStackTrace(); }finally{ try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } } public class ThreadsCopyFile { /** * * @param sourcePath 原始檔路徑 * @param targetPath 目標檔案路徑 * @param ThreadNums 設定的執行緒數 * @throws IOException */ public void startCopy(String sourcePath, String targetPath, int ThreadNums) throws IOException{ long fileLength = new File(sourcePath).length(); //很有可能檔案長度執行緒不能均分下載,預留一個執行緒複製最後剩餘的部分 long segmentLength = fileLength/(ThreadNums-1); int i; for (i = 0; i < ThreadNums-1; i++) { new CopyFileThread(sourcePath, targetPath, i*segmentLength, (i+1)*segmentLength).start(); } new CopyFileThread(sourcePath, targetPath, i*segmentLength, fileLength).start(); } public static void main(String[] args) throws IOException { //demo中實現的是將e盤中這個目錄下的電影複製到d盤下的tttt.rmvb ThreadsCopyFile tcf = new ThreadsCopyFile(); String sourcePath = "E:\\NewFile\\AppData\\Xunlei\\[陽光電影www.ygdy8.com].金剛狼3:殊死一戰.HD.720p.中英雙字幕.rmvb"; String targetPath = "D:\\tttt.rmvb"; tcf.startCopy(sourcePath, targetPath, 3); } }

總結

總之來說,如果執行緒越多,buffer區越大,耗費的記憶體資源也就越多,但是相對的能提升複製的效率。是一種以資源換取效率的方式,因此需要的執行緒數量的設定,需要考慮到資源的消耗。