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(); } } }