使用多线程和IO流编写文件复制功能类

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值