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

来源:互联网 发布:便宜mp3知乎 编辑:程序博客网 时间:2024/04/23 23:43
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);}@Overridepublic 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();}}



0 0
原创粉丝点击