Java.io.BufferedOutputStream.Write() 方法



描述

該 **java.io.BufferedOutputStream.write(byte[], int, int)** 方法從指定的位元組陣列 **b** 的偏移量 **off** 開始寫入 **len** 個位元組到流中。如果長度與該流的緩衝區一樣大,則會重新整理緩衝區並將位元組直接寫入輸出流。

宣告

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

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

引數

  • **b** − 位元組陣列作為源資料

  • **off** − 源中的起始偏移量

  • **len** − 要寫入流的位元組數

返回值

此方法不返回值。

異常

**IOException** − 如果發生 I/O 錯誤。

示例

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

package com.tutorialspoint;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class BufferedOutputStreamDemo {
   public static void main(String[] args) throws Exception {
      BufferedOutputStream bos = null;
		
      try {
         // create new output streams.
         baos = new ByteArrayOutputStream();
         bos = new BufferedOutputStream(baos);

         // assign values to the byte array 
         byte[] bytes = {1, 2, 3, 4, 5};

         // write byte array to the output stream
         bos.write(bytes, 0, 5);

         // flush the bytes to be written out to baos
         bos.flush();

         for (byte b:baos.toByteArray()) {
            
            // prints byte
            System.out.print(b);
         }
      } catch(IOException e) {
         // if any IOError occurs
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(baos!=null)
            baos.close();
         if(bos!=null)
            bos.close();
      }
   }
}

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

12345
java_io_bufferedoutputstream.htm
廣告
© . All rights reserved.