Java(四)

來源:互聯網
上載者:User

標籤:

下面的代碼可以實現以位元組為單位複製檔案的功能,適合複製非文本類型的檔案,為了更清楚的觀測運行速率,我加入了程式計時器,代碼如下:

 1 import java.io.FileInputStream; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4  5 public class Yuan { 6     /** 7      * @param args 8      */ 9     public static void main(String[] args) {10         long startMili=System.currentTimeMillis();11         try {12             FileInputStream fis = new FileInputStream ("a.mp3");13             FileOutputStream fos = new FileOutputStream ("temp.mp3");14             int read = fis.read();        15             while ( read != -1 ) {16                 fos.write(read);    17                 read = fis.read();18             }            19             fis.close();20             fos.close();21         } catch (IOException e) {22             e.printStackTrace();23         }24         long endMili=System.currentTimeMillis();25         System.out.println("總耗時為:"+(endMili-startMili)+"毫秒");26     }27 }

 

運行效果:

 

但是,這段代碼在複製如mp3等大檔案時,運行效率很低,課後我對以上代碼進行了改進:

 1 import java.io.FileInputStream; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4  5 public class Copys { 6     /** 7      * @param args 8      */ 9     public static void main(String[] args) {10         long startMili=System.currentTimeMillis();11         try {12             FileInputStream fis = new FileInputStream ("a.mp3");13             FileOutputStream fos = new FileOutputStream ("temp.mp3");    14             byte[] bys = new byte[1024];15             int len = 0;16             while ((len = fis.read(bys)) != -1) {17                 fos.write(bys, 0, len);18             }            19             fis.close();20             fos.close();21         } catch (IOException e) {22             e.printStackTrace();23         }24         long endMili=System.currentTimeMillis();25         System.out.println("總耗時為:"+(endMili-startMili)+"毫秒");26     }27 }

註:紅色代碼為改進前後的代碼對比

運行效果:

 

 

 

總結:

1. 位元組流拷貝檔案步驟如下:

 ①.構造檔案位元組輸入輸出資料流

 ②.建立一個位元組數組,用來指定每次複製的位元組大小

 ③.輸入資料流從源檔案讀取位元組,輸出資料流將位元組寫入檔案

2. fis.read(bys)的作用是從源檔案最多讀取bys.length位元組的資料送給bys數組,返回的是讀入的位元組總數。

   本例中bys.length的長度指定為1024000,當最後一次不足1024000,例如只剩下5000位元組時,返回的就是5000,此時所有位元組讀取完畢。下一次讀入時由於已到達檔案末尾,返回-1。

   fos.write(bys, 0, len)意思是將byte數組從位移量0開始的n個位元組寫入檔案輸出資料流。

3. 程式結束後要關閉輸入輸出資料流。

 

Java(四)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.