使用多线程和IO流编写文件复制功能类
发布日期:2022-02-09 20:39:09 浏览次数:5 分类:技术文章

本文共 1947 字,大约阅读时间需要 6 分钟。

CopyFile类

package copyfile;import java.io.*;import java.text.DecimalFormat;/** * 文件复制类 * @author Administrator * */public class FileCopy extends Thread {        private File src;//待读取的源文件    private File dest;//待写入的目标文件        public FileCopy(String src,String dest){        this.src = new File(src);        this.dest = new File(dest);    }    @Override    public void run() {        FileInputStream is = null;        FileOutputStream os = null;                try {            is = new FileInputStream(src);            os = new FileOutputStream(dest);                        byte[] b = new byte[1024];            int length = 0;                        //获取源文件大小            long len = src.length();            //已复制文件的字节数            double temp = 0 ;             //数字格式化,显示百分比            DecimalFormat df = new DecimalFormat("##.00%");            while((length = is.read(b))!=-1){                //输出字节                os.write(b, 0, length);                //获取已下载的大小,并且转换成百分比                temp += length;                double d = temp/len;                System.out.println(src.getName()+"已复制的进度:"+df.format(d));            }            System.out.println(src.getName()+"复制完成!");                    } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                if (is != null) {                    is.close();                }                 if(os!=null){                    os.close();                }            } catch (Exception e) {                e.printStackTrace();            }        }                    }}
测试类

package copyfile;

public class Test {
public static void main(String[] args) {
FileCopy cf = new FileCopy("D:\\1.txt","D:\\test\\1.txt");
FileCopy cf2 = new FileCopy("D:\\2.txt","D:\\test\\2.txt");
FileCopy cf3 = new FileCopy("D:\\3.txt","D:\\test\\3.txt");
cf.start();
cf2.start();
cf3.start();
}
}

转载地址:https://blog.csdn.net/JohneyWu/article/details/75103360 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:使用Maven创建SpringBoot
下一篇:编译时异常与运行时异常区别

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月15日 04时16分58秒