Java基礎複習:檔案拷貝

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.