“我們將從文件輸入/輸出的流開始。但首先要做的是。”

有兩個用於讀取和寫入文件的類: FileInputStreamFileOutputStream。正如您可能已經猜到的那樣,FileInputStream可以順序地從文件中讀取字節,而FileOutputStream可以順序地將字節寫入文件。以下是這些類具有的方法:

方法 該方法的作用
FileInputStream(String fileName);
— 這是構造函數。它允許您指定磁盤上文件的名稱,創建的對象將從中讀取數據。
int read();
— 此方法從文件中讀取一個字節並將其返回。返回值擴展為 int。
int available();
— 此方法返回未讀(可用)字節數。
void close();
— 此方法“關閉”流。當你完成流的工作時,你會調用它。
然後該對象執行關閉文件等所需的內務處理操作。
此時,您不能再從流中讀取任何數據。

只是為了好玩,讓我們計算一個文件中所有字節的總和。代碼如下所示:

總結文件中的所有字節
public static void main(String[] args) throws Exception
{
 //Create a FileInputStream object bound to «c:/data.txt».
 FileInputStream inputStream = new FileInputStream("c:/data.txt");
 long sum = 0;

 while (inputStream.available() > 0) //as long as there are unread bytes
 {
  int data = inputStream.read(); //Read the next byte
  sum +=  data; //Add it to the running total
 }
 inputStream.close(); // Close the stream

 System.out.println(sum); // Display the sum on the screen.
}

“我們已經研究過類似的事情。FileOutputStream 是如何組織的?”

“好的。看看這個:”

方法 該方法的作用
FileOutputStream (String fileName);
“這是構造函數。它允許您指定磁盤上文件的名稱,創建的對象將向該文件寫入數據。”
void write(int data);
“此方法寫入下一個字節,將數據截斷為一個字節。”
void flush();
“要寫入的數據往往先在內存中收集成大塊,然後才寫入磁盤。”

flush 命令強制將所有未保存的信息寫入磁盤。

void close();
“這個方法 «關閉» 流。當你完成對流的處理時調用它。”
然後該對象執行關閉文件等所需的內務處理操作。

您不能再向流中寫入數據,並且會自動調用 flush。

“就是這樣?”

“是的,實際上只有一種寫入方法:write()。它一次只寫入一個字節。但它可以讓您向文件寫入盡可能多的信息。”

編程是將一個大而復雜的任務分成許多小任務的過程。基本上相同的過程在這裡發生:讀取和寫入大塊數據被分解為讀取和寫入一口大小的塊——一次一個字節。

以下是如何使用這些類將文件複製到磁盤上:

複製磁盤上的文件
public static void main(String[] args) throws Exception
{
 //Create a stream to read bytes from a file
 FileInputStream inputStream = new FileInputStream("c:/data.txt");
 //Create a stream to write bytes to a file
 FileOutputStream outputStream = new FileOutputStream("c:/result.txt");

 while (inputStream.available() > 0) //as long as there are unread bytes
 {
  int data = inputStream.read(); // Read the next byte into the data variable
  outputStream.write(data); // and write it to the second stream
 }

 inputStream.close(); //Close both streams. We don't need them any more.
 outputStream.close();
}

“謝謝,Rishi。我終於明白這段代碼是如何工作的了。”