創建一個復制功能類,繼承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 }