您的位置:首页 > 编程语言 > Java开发

使用Java的多线程和IO流写一个文件复制功能类

2016-07-21 15:44 706 查看
创建一个复制功能类,继承Thread类,重写run()方法,把FileInputStream和FileOutputStream输入输出流写在run()方法内。示例代码如下:

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

}

}


在测试类中调用复制功能类

public class FileCopyTest {

public static void main(String[] args) {

FileCopy cf = new FileCopy("D:\\720.txt","D:\\test\\1.txt");
FileCopy cf2 = new FileCopy("D:\\721.txt","D:\\test\\2.txt");
FileCopy cf3 = new FileCopy("D:\\123.txt","D:\\test\\3.txt");
cf.start();
cf2.start();
cf3.start();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: