使用Java的多线程和IO流写一个文件复制功能类
创建一个复制功能类,继承Thread类,重写run()方法,把FileInputStream和FileOutputStream输入输出流写在run()方法内。示例代码如下:
1 import java.io.*; 2 import java.text.DecimalFormat; 3 /** 4 * 文件复制类 5 * @author Administrator 6 * 7 */ 8 public class FileCopy extends Thread { 9 10 private File src;//待读取的源文件 11 private File dest;//待写入的目标文件 12 13 public FileCopy(String src,String dest){ 14 this.src = new File(src); 15 this.dest = new File(dest); 16 } 17 18 @Override 19 public void run() { 20 FileInputStream is = null; 21 FileOutputStream os = null; 22 23 try { 24 is = new FileInputStream(src); 25 os = new FileOutputStream(dest); 26 27 byte[] b = new byte[1024]; 28 int length = 0; 29 30 //获取源文件大小 31 long len = src.length(); 32 //已复制文件的字节数 33 double temp = 0 ; 34 //数字格式化,显示百分比 35 DecimalFormat df = new DecimalFormat("##.00%"); 36 while((length = is.read(b))!=-1){ 37 //输出字节 38 os.write(b, 0, length); 39 //获取已下载的大小,并且转换成百分比 40 temp += length; 41 double d = temp/len; 42 System.out.println(src.getName()+"已复制的进度:"+df.format(d)); 43 } 44 System.out.println(src.getName()+"复制完成!"); 45 46 } catch (FileNotFoundException e) { 47 e.printStackTrace(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 }finally{ 51 try { 52 if (is != null) { 53 is.close(); 54 } 55 if(os!=null){ 56 os.close(); 57 } 58 } catch (Exception e) { 59 e.printStackTrace(); 60 } 61 } 62 63 } 64 65 }
在测试类中调用复制功能类
1 public class FileCopyTest { 2 3 public static void main(String[] args) { 4 5 FileCopy cf = new FileCopy("D:\\720.txt","D:\\test\\1.txt"); 6 FileCopy cf2 = new FileCopy("D:\\721.txt","D:\\test\\2.txt"); 7 FileCopy cf3 = new FileCopy("D:\\123.txt","D:\\test\\3.txt"); 8 cf.start(); 9 cf2.start(); 10 cf3.start(); 11 12 } 13 14 }