天天看點

FileInputStream 之read(byte [] b)方法

FileInputStream是InputStream的子類,由名稱上就可以知道, FileInputStream主要就是從指定的File中讀取資料至目的地。

FileOutputStream是OutputStream的子類,顧名思義,FileOutputStream主要就是從來源地寫入資料至指定的File中。

标準輸入輸出串流物件在程式一開始就會開啟,但隻有當您建立一個FileInputStream或FileOutputStream的執行個體時,實際的串流才會開啟,而不使用串流時,也必須自行關閉串流,以釋放與串流相依的系統資源。

下面這個程式可以複制檔案,程式先從來源檔案讀取資料至一個位元緩沖區中,然後再将位元陣列的資料寫入目的檔案:

  • FileStreamDemo.java
package onlyfun.caterpillar;



import java.io.*; 



public class FileStreamDemo {

public static void main(String[] args) {

try { 

byte[] buffer = new byte[1024]; 



FileInputStream fileInputStream = 

new FileInputStream(new File(args[0])); 

FileOutputStream fileOutputStream = 

new FileOutputStream(new File(args[1])); 



System.out.println("複制檔案:" + 

fileInputStream.available() + "位元組"); 

while(true) { // 從來源檔案讀取資料至緩沖區 

if(fileInputStream.available() < 1024) { 

int remain; 

while((remain = fileInputStream.read())

!= -1) {

fileOutputStream.write(remain); 

}

break; 

} 

else { 

fileInputStream.read(buffer); 

// 将陣列資料寫入目的檔案 

fileOutputStream.write(buffer); 

} 

} 



// 關閉串流 

fileInputStream.close(); 

fileOutputStream.close(); 



System.out.println("複制完成"); 

} 

catch(ArrayIndexOutOfBoundsException e) { 

System.out.println(

"using: java FileStreamDemo src des"); 

e.printStackTrace(); 

} 

catch(IOException e) { 

e.printStackTrace(); 

} 

}

}

      

這個程式示範了兩個 read() 方法,一個可以讀入指定長度的資料至陣列,一個一次可以讀入一個位元組,每次讀取之後,讀取的名額都會往前進,您使用available()方法獲得還有多少位元組可以讀取;除了使用File來建立FileInputStream、FileOutputStream的執行個體之外,您也可以直接使用字串指定路徑來建立。

不使用串流時,記得使用close()方法自行關閉串流,以釋放與串流相依的系統資源。

繼續閱讀