用文件流來拷貝一個文件,用到文件字節輸入流(FileInputStream)和文件字節輸出流(FileOutputStream),用輸入流把字節文件讀到緩沖數組中,然后將緩沖數組中的字節寫到文件中,就很好的完成了文件的復制操作。
來,看一下代碼
1 //1.創建源和目標
2 File srcFile = new File("C:/Users/15626/Desktop/test/123.txt"); 3 File targetFile = new File("C:/Users/15626/Desktop/test/123_copy.txt"); 4 //2.創建輸入流和輸出流
5 FileInputStream in = new FileInputStream(srcFile); 6 FileOutputStream out = new FileOutputStream(targetFile); 7 //3.輸入 輸出操作
8 byte[] buffer = new byte[10]; 9 int len = 0; 10 while((len = in.read(buffer)) != -1){ 11 //String str = new String(buffer,0,len);
12 out.write(buffer, 0, len);; 13 } 14 //4.關閉資源文件
15 in.close(); 16 out.close();
完了你會發現出現了
全是錯誤,那是因為輸出輸出可能會出現異常,可能你會直接拋出去,那么怎么正確處理這些異常情況?
當然是try-catch-finally
1 FileInputStream in = null; 2 FileOutputStream out = null; 3 try{//可能出現問題的代碼 4 //1.創建源和目標 5 File srcFile = new File("C:/Users/15626/Desktop/test/123.txt"); 6 File targetFile = new File("C:/Users/15626/Desktop/test/123_copy.txt"); 7 //2.創建輸入流和輸出流 8 in = new FileInputStream(srcFile); 9 out = new FileOutputStream(targetFile); 10 //3.輸入 輸出操作 11 byte[] buffer = new byte[10]; 12 int len = 0; 13 while((len = in.read(buffer)) != -1){ 14 //String str = new String(buffer,0,len); 15 out.write(buffer, 0, len);; 16 } 17 }catch(Exception e){//處理異常 18 e.printStackTrace(); 19 }finally{ 20 //4.關閉資源文件 21 try{ 22 in.close(); 23 out.close(); 24 }catch(Exception e){ 25 e.printStackTrace(); 26 } 27 }
好了,到這里之后異常終於消除了,然而這個程序還是有問題:
當程序執行到 in = new FileInputStream(srcFile); 的時候,假設有個異常,然后程序后去處理這個異常,根本沒有執行下面的程序,然而這時候out還是null,在finally中還關閉了out,本身沒有異常,你制造了異常。 那么怎么解決呢?
那么將它們分開try就ok了:
1 finally{ 2 //4.關閉資源文件
3 try{ 4 if(in != null){ 5 in.close(); 6 } 7 }catch(Exception e){ 8 e.printStackTrace(); 9 } 10 try{ 11 if(out != null){ 12 out.close(); 13 } 14
15 }catch(Exception e){ 16 e.printStackTrace(); 17 } 18 }
到這你會發現程序的主體都在上面,然而下面卻處理了這么多異常還有關閉資源,程序變得很難看!然而java7之后,出現了自動關閉資源的機制,我去,這感情好啊,來欣賞一下:
1 File srcFile = new File("C:/Users/15626/Desktop/test/123.txt"); 2 File targetFile = new File("C:/Users/15626/Desktop/test/123_copy.txt"); 3 try(//打開資源的代碼
4 FileInputStream in = new FileInputStream(srcFile); 5 FileOutputStream out = new FileOutputStream(targetFile); 6 ){ 7 //3.輸入 輸出操作
8 byte[] buffer = new byte[10]; 9 int len = 0; 10 while((len = in.read(buffer)) != -1){ 11 //String str = new String(buffer,0,len);
12 out.write(buffer, 0, len);; 13 } 14 }catch(Exception e){ 15 e.printStackTrace(); 16 }
嗯,這個新特性很好!
1 try(打開資源的代碼 ){ 2
3 可能存在異常的代碼 4
5 }catch(){ 6
7 處理異常信息 8
9 }