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

本文提供了一个使用Java实现文件复制的示例代码。通过继承Thread类并覆盖run方法,可以并行复制多个文件。示例展示了如何从源文件读取数据,并将其写入到目标文件中,同时显示文件复制进度。

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



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();
			}
		}

	}
}
、、、、、、



public class Test {

	public static void main(String[] args) {
		CopyFile cf1 = new CopyFile("E:\\a.txt", "F:\\a.txt");
		CopyFile cf2 = new CopyFile("E:\\b.txt", "F:\\b.txt");
		CopyFile cf3 = new CopyFile("E:\\c.txt", "F:\\c.txt");

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

	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值