import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.text.DecimalFormat; import java.util.Date; class FileCopy implements Runnable{ private File src;//源文件 private File tar;//目標文件 private int n;//分幾部分 private int no;//每部分的編號 Date startDate = new Date(); public FileCopy(File src, File tar, int n, int no) { this.src = src; this.tar = tar; this.n = n; this.no = no; } @Override public void run() { try { RandomAccessFile rafsrc = new RandomAccessFile(src,"r"); String fileName = src.getName(); tar = new File(tar + File.separator + fileName); RandomAccessFile raftar = new RandomAccessFile(tar,"rw"); long len = src.length(); long size = len % n == 0 ? len / n : len / n + 1;//每部分的字節數 byte[] b = new byte[1024 * 8];//每次讀取的文件大小 int num = 0;//每次讀取的字節數 long start = size * no;//讀寫的起始位置 rafsrc.seek(start); raftar.seek(start); double sum = 0;//累加每次讀取個數 DecimalFormat df = new DecimalFormat("##.00%"); while((num = rafsrc.read(b)) != -1 && sum < size){ raftar.write(b, 0, num); sum += num; double d = sum / len; System.out.println(fileName + "已復制的進度:" + df.format(d)); } System.out.println(src.getName() + "復制完成!"); System.out.println("復制文件用" + n + "線程,用時:" + (new Date().getTime()-startDate.getTime())); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e1){ e1.printStackTrace(); } } } /** * @Description:ლ【多線程】ლ->復制文件 * @Param: * @Return: * @Author: Mr.li * @Date: 2020/1/3 */ public class TestFileCopy { public static void main(String[] args){ File src = new File("/Users/lzl/Desktop/personal_word/a/img_tx.zip"); File tar = new File("/Users/lzl/Desktop/personal_word/b"); int n = 5; //分幾部分復制 for(int i = 0;i < n; i++){//每一部分的編號 new Thread(new FileCopy(src, tar, n, i)).start(); } } }