(1)利用位元組輸入輸出資料流完成檔案拷貝
package day20.filecopy;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class Demo1 {public static void main(String[] args) {File srcF = new File("d:/Test/筆記.txt");File destF = new File("d:/Test/hi.txt");fileCopy(srcF,destF);//無論是文本還是圖片,都能拷貝成功}public static void fileCopy(File srcFile,File destFile){//檔案非空檢查if(srcFile == null || destFile == null){System.out.println("The file is null");return ;}InputStream is = null;OutputStream os = null;try {is = new FileInputStream(srcFile);os = new FileOutputStream(destFile);//len表示已經讀取的位元組數,若len!=-1表示檔案讀完了int len = 0;//buff緩衝區byte[] buff = new byte[1024];while((len=is.read(buff))!=-1){os.write(buff, 0, len);}System.out.println("您的檔案拷貝成功!");} catch (IOException e) {e.printStackTrace();} finally {try {os.close();//先關os} catch (IOException e) {e.printStackTrace();} finally {try {is.close();//無論os是否關閉都應該關閉is} catch (IOException e) {e.printStackTrace();}}}}}
這種方式下的拷貝操作最複雜的地方在異常處理,尤其是在關閉資源時,異常處理更為累贅。
從java 7開始,新增了“資源自動關閉”的特性,稱為 try-with-resource
(2)利用自動關閉資源新特性完成檔案拷貝操作
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class Demo2 {public static void main(String[] args) {File srcF = new File("d:/Test/筆記.txt");File destF = new File("d:/Test/hi.txt");fileCopy(srcF,destF);//無論是文本還是圖片,都能拷貝成功}public static void fileCopy(File srcFile,File destFile){//檔案非空檢查if(srcFile == null || destFile == null){System.out.println("The file is null");return ;}try(InputStream is = new FileInputStream(srcFile);OutputStream os = new FileOutputStream(destFile);) {//len表示已經讀取的位元組數,若len!=-1表示檔案讀完了int len = 0;//buff緩衝區byte[] buff = new byte[1024];while((len=is.read(buff))!=-1){os.write(buff, 0, len);}System.out.println("您的檔案拷貝成功!");} catch (IOException e) {e.printStackTrace();} }}
如上,通過這種方式,大大的減少了異常處理的代碼,也使得程式的結構更為清晰明了。
其格式如下:
try(//在這裡聲明變數,開啟資源//要求對象必須實現java.lang.AutoCloseable介面){//這裡進行IO操作}catch(IOException e){e.printStackTrace();}