栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

利用多线程和IO流进行文件复制

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

利用多线程和IO流进行文件复制

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

public class oneThreadCopy {
    public static void main(String[] args) throws FileNotFoundException {
        //源文件
        File source=new File("f:/test/navicat150_premium_cs_x64.exe");
        //目标文件
        File destFile=new File("f:/test/navicat4.exe");
        //获取文件长度
        long length=source.length();
        //预计线程数
        long threadNum=3;
        //分割文件
        long average=length/threadNum;
        //创建多个线程
        for (int i = 0; i < threadNum; i++) {
            //0~100,101~200,201~300
            //开始位置
            long start=i*(average+1);
            //结束位置
            long end=(i+1)*average;
            //启动线程
            new Thread(new CopyThread(start,end,source,destFile)).start();
        }
        //有剩余在增加一个线程
        if(length%threadNum!=0) {
            new Thread(new CopyThread(average*threadNum+1, length, source, destFile)).start();
        }
    }
}
class CopyThread implements Runnable{
    private long start;
    private long end;
    public RandomAccessFile rsource=null;
    public RandomAccessFile rdestFile=null;
    public CopyThread(long start, long end, File source, File destFile) throws FileNotFoundException {
        this.start = start;
        this.end = end;
        this.rsource=new RandomAccessFile(source, "rw");
        this.rdestFile=new RandomAccessFile(destFile, "rw");
    }
    @Override
    public void run() {
        try {
            //光标移到初始位置
            rsource.seek(start);
            rdestFile.seek(start);
            //缓存区
            byte []bytes=new byte[1024*1024];
            //读取的个数
            int len=0;
            //源文件里光标的位置
            long point=rsource.getFilePointer();
            while(point<=end&&(len=rsource.read())!=-1) {
                //把长度为len的字节写入
                rdestFile.write(bytes,0,len);
                //光标移动len
                point+=len;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                rsource.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                rdestFile.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
    
}
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325555.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号