IO 单个文件的多线程拷贝

package FileCopyThread;                         //自建的包,根据个人调整

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

public class FileCopy {
    public static void main(String[] args) {
        
        int start = (int)System.currentTimeMillis();
        try {
            RandomAccessFile raf = new RandomAccessFile(new File("E:/11.txt"), "r");
            int fileLen = (int)raf.length();
            int nums = 20;
            int distance = (int)(fileLen/nums);
            
            new ThreadFileCopy(0, distance - 1).start();;
            for(int i = 1; i <= nums - 2; i++){
                new ThreadFileCopy(distance*i, distance*(i+1) - 1).start();
            }
            new ThreadFileCopy(distance*(nums-1), fileLen).start();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int end = (int)System.currentTimeMillis();
        System.out.println("耗时:" + (end - start));
        
    }
}
package FileCopyThread;                         //自建的包根据个人调整

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

public class ThreadFileCopy extends Thread{
    final String oldPath = "E:/11.txt";
    final String newPath = "F:/22.txt";
    
    RandomAccessFile oraf = null;
    RandomAccessFile nraf = null;
    
    private int startPos = 0;
    private int endPos = 0;
    final int bufSize = 10240 * 5;
    public ThreadFileCopy(){
        
    }
    
    public ThreadFileCopy(int startPos, int endPos){
        this.startPos = startPos;
        this.endPos = endPos;
    }
    
    @Override
    public void run() {
        
        try {
            oraf = new RandomAccessFile(new File(oldPath), "r");
            nraf = new RandomAccessFile(new File(newPath), "rw");
            
            oraf.seek(startPos);
            nraf.seek(startPos);
            
            byte[] bytes = new byte[bufSize];
            int len;
            while(endPos - startPos > 0){
                len = (int)((endPos - startPos) > bufSize ? bufSize :(endPos - startPos));
                oraf.read(bytes, 0, len);
                nraf.write(bytes, 0, len);
                endPos -= len;
                System.out.println(Thread.currentThread().getName() 
                        + "读取了" + len + "个字节");
            }
            
            
            
            oraf.close();
            nraf.close();
            
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/854594834-YT/p/10527481.html