Java.io.FileOutputStream.write() 方法



描述

java.io.FileOutputStream.write(byte[] b, int off, int len) 方法將指定位元組陣列中從偏移量 off 開始的 len 個位元組寫入此檔案輸出流。

宣告

以下是 java.io.FileOutputStream.write(byte[] b, int off, int len) 方法的宣告:

public void write(byte[] b, int off, int len)

引數

  • b - 源緩衝區。

  • off - 資料的起始偏移量。

  • len - 要寫入的位元組數。

返回值

此方法不返回值。

異常

IOException - 如果發生任何 I/O 錯誤。

示例

以下示例演示了 java.io.FileOutputStream.write(byte[] b, int off, int len) 方法的使用。

package com.tutorialspoint;

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

public class FileOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      FileOutputStream fos = null;
      FileInputStream fis = null;
      byte[] b = {65,66,67,68,69};
      int i = 0;
      char c;
      
      try {
         // create new file output stream
         fos = new FileOutputStream("C://test.txt");
         
         // writes byte to the output stream
         fos.write(b, 2, 3);
         
         // flushes the content to the underlying stream
         fos.flush();
         
         // create new file input stream
         fis = new FileInputStream("C://test.txt");
         
         // read till the end of the file
         while((i = fis.read())!=-1) {
         
            // convert integer to character
            c = (char)i;
            
            // prints
            System.out.print(c);
         }
         
      } catch(Exception ex) {
         // if an error occurs
         ex.printStackTrace();
      } finally {
         // closes and releases system resources from stream
         if(fos!=null)
            fos.close();
         if(fis!=null)
            fis.close();
      }
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

CDE
java_io_fileoutputstream.htm
廣告