Java FileOutputStream.write(byte[] b)方法範例

2019-10-16 22:14:27

FileOutputStream.write(byte[] b)方法具有以下語法。

public void write(byte[] b)  throws IOException

範例

在下面的程式碼顯示如何使用FileOutputStream.write(byte[] b)方法。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    byte[] b = { 65, 66, 67, 68, 69 };
    int i = 0;
    FileOutputStream fos = new FileOutputStream("C://test.txt");

    fos.write(b);

    // flushes the content to the underlying stream
    fos.flush();

    // create new file input stream
    FileInputStream fis = new FileInputStream("C://test.txt");

    // read till the end of the file
    while ((i = fis.read()) != -1) {
      // convert integer to character
      char c = (char) i;
      System.out.print(c);
    }
  }
}