zoukankan      html  css  js  c++  java
  • 实现多线程拷贝一个文件

    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();
            }
    
        }
    }
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    js4——字符转化
    js3——表格下拉
    笔记展现
    js2——定时跳转
    js学习——1
    明明在/etc/my.cnf 配置了mysql.sock,为什么会在/var/lib/mysql/mysql.sock 里边寻找
    RBAC用户权限管理数据库设计
    mysql 字节问题,中文和数字
    PHP闭包
    一致性哈希算法原理
  • 原文地址:https://www.cnblogs.com/name-lizonglin/p/12144984.html
Copyright © 2011-2022 走看看