多线程复制一个文件

需求:多个线程复制一个文件(ZIP文件)到另一个文件里。

package cn.ba.watchFile.downLoadFile.downDemo.singleFile;

import java.io.File;
import java.util.Date;

/**
 * 复制文件
 * n个线程
 * @author Administrator
 *
 */
public class TestFileCopy {
    public static void main(String[] args) {
        File src = new File("F:/zip/145-088865366-330700-330700-1499140617-51881.zip");  
        File tar = new File("F:/zipbck");  
        int n=5;
        Date startDate = new Date();
        // 分几部分复制  
        for (int i = 0; i < n; i++) {// 每一部分的编号  
            new Thread(new FileCopy(src, tar, n, i)).start();  
        } 
        System.out.println("复制文件用"+n+"线程,用时:"+(new Date().getTime()-startDate.getTime()));
    }
}
package cn.ba.watchFile.downLoadFile.downDemo.singleFile;

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

public class FileCopy implements Runnable{
     private File src;// 源文件  
        private File tar;// 目标文件  
        private int n;// 分几部分  
        private int no;// 每部分的编号  
      
        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() {
        // TODO Auto-generated method stub
        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);  
            int sum = 0;// 累加每次读取个数  
            while ((num = rafsrc.read(b)) != -1 && sum < size) {  
                raftar.write(b, 0, num);  
                sum += num;  
            }  
  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        }
    }

}
原文地址:https://www.cnblogs.com/kwzblog/p/8892385.html