使用多线程实现多个文件同步复制功能,并在控制台显示复制的进度,进度以百分比表示

本文介绍如何利用多线程技术实现在控制台中显示百分比进度的多个文件同步复制功能,包括项目结构、核心代码及运行效果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:项目结构

 

2:代码

    1:CopyFile


package tianyi.demo4;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;


public class CopyFile extends Thread {

    public File older;// 源文件路径
    public File newer;// 复制目标路径

    public CopyFile(String older, String newer) {
        this.older = new File(older);
        this.newer = new File(newer);
    }



    @Override
    public void run() {

        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(older);
            fos = new FileOutputStream(newer);

            byte[] b = new byte[1024];// 声明一个字节数组,每次读取的数据存到该字节数组里
            int length = 0;// 返回每次读取的数据长度
            long len = older.length();// 获取源文件的长度
            double temp = 0;
            DecimalFormat df = new DecimalFormat("##%");

            while ((length = fis.read(b)) != -1) {
                fos.write(b, 0, length);// 把每次读取的内容,输出到目标路径文件中
                temp += length;// 把每次读取的数据长度累加
                double d = temp / len;// 计算出已经读取的长度占文件总长度的比率
                int jd = (int) d;
                if (jd % 10 == 0) {

                    System.out.println(older.getName() + "文件复制了:" + df.format(d));

                }

            }

            System.out.println(older.getName() + "复制完毕!");
        } catch (IOException e) {

            e.printStackTrace();

        } finally {
            try {

                fis.close();
                fos.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }



    }

}

        2:Test


package tianyi.demo4;

public class Test {

    public static void main(String[] args) {

        CopyFile cf1 = new CopyFile("F:\\helloworld\\hang1.txt", "F:\\helloworld\\jia1.txt");
        CopyFile cf2 = new CopyFile("F:\\helloworld\\hang2.txt", "F:\\helloworld\\jia2.txt");
        CopyFile cf3 = new CopyFile("F:\\helloworld\\hang3.txt", "F:\\helloworld\\jia3.txt");

        cf1.start();
        cf2.start();
        cf3.start();

    }

}

3:效果展示

 

 

 

 

 

 

 

 

 

 

 


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值