Java.io.OutputStream.write() 方法



描述

java.io.OutputStream.write(byte[] b, int off, int len) 方法將從指定位元組陣列中從偏移量 off 開始的 len 個位元組寫入此輸出流。write(b, off, len) 的通用約定是,陣列 b 中的一些位元組將按順序寫入輸出流;元素 b[off] 是寫入的第一個位元組,而 b[off+len-1] 是此操作寫入的最後一個位元組。

OutputStream 的 write 方法對要寫出的每個位元組呼叫一個引數的 write 方法。鼓勵子類覆蓋此方法並提供更有效的實現。

如果 b 為 null,則丟擲 NullPointerException。如果 off 為負數,或 len 為負數,或 off+len 大於陣列 b 的長度,則丟擲 IndexOutOfBoundsException。

宣告

以下是 java.io.OutputStream.write() 方法的宣告。

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

引數

  • b - 資料。

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

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

返回值

此方法不返回值。

異常

IOException - 如果發生 I/O 錯誤。特別是,如果輸出流已關閉,則會丟擲 IOException。

示例

以下示例顯示了 java.io.OutputStream.write() 方法的使用。

package com.tutorialspoint;

import java.io.*;

public class OutputStreamDemo {
   public static void main(String[] args) {
      byte[] b = {'h', 'e', 'l', 'l', 'o'};
      
      try {
         // create a new output stream
         OutputStream os = new FileOutputStream("test.txt");

         // craete a new input stream
         InputStream is = new FileInputStream("test.txt");

         // write something
         os.write(b, 0, 3);

         // read what we wrote
         for (int i = 0; i < 3; i++) {
            System.out.print("" + (char) is.read());
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

hel
java_io_outputstream.htm
廣告

© . All rights reserved.