Java -- 多线程文件复制

题目描述:

  • 实现文件复制功能
  • 多线程实现文件从一个目录复制到另一个目录
  • @param sourceFile : 给定源文件路径名
  • @param desPath : 复制点文件路径

在这里插入图片描述
代码:

package fileio20180924;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.omg.CORBA.PUBLIC_MEMBER;

/**
 * 实现文件复制功能
 * 多线程实现文件从一个目录复制到另一个目录
 * @param sourceFile : 给定源文件路径名
 * @param desPath : 复制点文件路径
 * @author Cue
 *
 */

public class FileCopy extends Thread {
	private File sourceFile;//待读取的源文件
	private File desPath;//待写入的目标文件
	
	public FileCopy(String sourceFile,String desPath){
		this.sourceFile = new File(sourceFile);
		this.desPath = new File(desPath);
	}
	
	public void run(){
		FileInputStream in = null;
		FileOutputStream out = null;
		
	try{	
		in = new FileInputStream(sourceFile);
		out = new FileOutputStream(desPath);
		
		byte[] b = new byte[1024];
		int length = 0;
		
		//获取源文件大小
		long len = sourceFile.length();
		//已复制文件的字节数
		double temp = 0;
		//数字格式化,显示百分比
		DecimalFormat dFormat = new DecimalFormat("##.00%");
		while((length = in.read(b)) != -1){
			//输出字节
			out.write(b, 0, length);
			//获取已下载的大小,并且转换成百分比
			temp += length;
			double d = temp/len;
			System.out.println(sourceFile.getName() + "已复制的进度 :"+dFormat.format(d));
		}
		System.out.println(sourceFile.getName() + "复制完成!");
	}catch(FileNotFoundException e){
		e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			try{
				if(in != null){
					in.close();
				}
				if(out != null){
					out.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FileCopy cf = new FileCopy("C:\\Users\\小玉沉香\\Desktop\\source\\1.txt","C:\\Users\\小玉沉香\\Desktop\\desPath\\11.txt");
		FileCopy cf2 = new FileCopy("C:\\Users\\小玉沉香\\Desktop\\source\\2.txt","C:\\Users\\小玉沉香\\Desktop\\desPath\\22.txt");
		FileCopy cf3 = new FileCopy("C:\\Users\\小玉沉香\\Desktop\\source\\3.txt","C:\\Users\\小玉沉香\\Desktop\\desPath\\33.txt");
		cf.start();
		cf2.start();
		cf3.start();
	}

}

输出结果:
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值