欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多个线程对象,复制同一个文件

程序员文章站 2022-06-02 15:46:26
...

利用多个线程可实现对文件的复制效率更高(小文件复制)
大文件复制还是采用单线程复制稳妥;

public class MyTest2 {

    public static void main(String[] args) throws IOException {

        new CopyThread(0).start();
        new CopyThread(1024*1024*2).start();
        new CopyThread(1024*1024*4).start();
        new CopyThread(1024*1024*6).start();
        new CopyThread(1024*1024*8).start();
    }

}

class CopyThread extends Thread{
    int filepointer;
    public CopyThread(int filepointer) {
        this.filepointer=filepointer;
    }

    @Override
    public void run() {
        try {

            File sourcefile = new File("C:\\Users\\Administrator\\Desktop\\test\\许巍-歌曲大联唱.mp3");
            File targetfile = new File("C:\\Users\\Administrator\\Desktop\\test\\许巍-歌曲大联唱copy.mp3");
            CopyFile(filepointer, sourcefile, targetfile);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void CopyFile(long filepointer, File sourcefile, File targetfile) throws IOException {

            RandomAccessFile read= new RandomAccessFile(sourcefile,"rw");
            RandomAccessFile write = new RandomAccessFile(targetfile, "rw");
            int len=0;
            byte[] bytes = new byte[0];
            bytes=new byte[1024*1024*2];
            read.seek(filepointer);
            write.seek(filepointer);
            len=read.read(bytes);
            write.write(bytes,0,len);

            filepointer = read.getFilePointer();
            System.out.println(filepointer);
            read.close();
            write.close();

    }
}