Java中的FileOutputStream。


這將資料寫入特定檔案或檔案描述符(逐位元組)。它通常用於使用原始位元組(例如影像)寫入檔案內容。

要使用此類寫入檔案內容:

  • 首先,需要透過傳遞一個字串變數或一個**File**物件來例項化此類,該物件代表要讀取的檔案的路徑。

FileOutputStream outputStream = new FileOutputStream("file_path");
or,
File file = new File("file_path"); FileOutputStream outputStream = new FileOutputStream (file);

也可以透過傳遞FileDescriptor物件來例項化FileOutputStream類。

FileDescriptor descriptor = new FileDescriptor(); FileOutputStream outputStream = new FileOutputStream(descriptor);
  • 然後使用**write()**方法的任何變體將資料寫入指定檔案:

    • **int write(int b)** - 此方法接受單個位元組並將其寫入當前OutputStream。

    • **int write(byte[] b)** - 此方法接受位元組陣列作為引數並將資料從位元組陣列寫入當前OutputStream。

    • **int write(byte[] b, int off, int len)** - 此方法接受位元組陣列、其偏移量 (int) 和其長度 (int) 作為引數並將內容寫入當前OutputStream。

示例

假設我們在**D:/images**目錄下有以下影像

以下程式讀取上述影像的內容並使用**FileOutputStream**類將其寫回另一個檔案。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileInputStreamExample {
   public static void main(String args[]) throws IOException {
      //Creating a File object
      File file = new File("D:/images/javafx.jpg");
      //Creating a FileInputStream object
      FileInputStream inputStream = new FileInputStream(file);
      //Creating a byte array
      byte bytes[] = new byte[(int) file.length()];
      //Reading data into the byte array
      int numOfBytes = inputStream.read(bytes);
      System.out.println("Data copied successfully...");
      //Creating a FileInputStream object
      FileOutputStream outputStream = new FileOutputStream("D:/images/output.jpg");
      //Writing the contents of the Output Stream to a file
      outputStream.write(bytes);
      System.out.println("Data written successfully...");
   }
}

輸出

Data copied successfully...
Data written successfully...

如果驗證給定的路徑,您可以觀察到生成的影像為:

更新於:2019年9月12日

274 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.