Java - ByteArrayOutputStream write(byte[] b, int off, int len)



描述

java ByteArrayOutputStream write(byte[] b, int off, int len) 方法將指定位元組陣列從偏移量 off 開始的 len 個位元組寫入此 ByteArrayOutputStream。

宣告

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

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

引數

  • b - 指定的緩衝區。

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

  • len - 要寫入的位元組長度。

返回值

此方法不返回值。

異常

示例 1

以下示例演示了 Java ByteArrayOutputStream write(byte[] b, int off, int len) 方法的使用。我們建立了一個 ByteArrayOutputStream 引用,然後用 ByteArrayOutputStream 物件對其進行初始化。現在我們使用 write() 方法將位元組陣列的一部分寫入輸出流,並使用 toString() 方法列印流的字串表示形式。最後,在 finally 塊中,我們使用 close() 方法關閉流。

package com.tutorialspoint;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      String str = "";      
      byte[] bs = {65, 66, 67, 68, 69};
      ByteArrayOutputStream baos = null;
      
      try {
         // create new ByteArrayOutputStream
         baos = new ByteArrayOutputStream();
      
         // write byte array to the output stream
         baos.write(bs, 2, 3);
         
         // converts buffer to string
         str = baos.toString();
         
         // print
         System.out.println(str);
         
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(baos!=null)
            baos.close();
      }   
   }
}

輸出

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

CDE

示例 2

以下示例演示了 Java ByteArrayOutputStream write(byte[] b, int off, int len) 方法的使用。我們建立了一個 ByteArrayOutputStream 引用,然後用 ByteArrayOutputStream 物件對其進行初始化。現在我們使用 write() 方法將整個位元組陣列寫入輸出流,並使用 toString() 方法列印流的字串表示形式。最後,在 finally 塊中,我們使用 close() 方法關閉流。

package com.tutorialspoint;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      String str = "";      
      byte[] bs = {65, 66, 67, 68, 69};
      ByteArrayOutputStream baos = null;
      
      try {
         // create new ByteArrayOutputStream
         baos = new ByteArrayOutputStream();
      
         // write byte array to the output stream
         baos.write(bs, 0, bs.length());
         
         // converts buffer to string
         str = baos.toString();
         
         // print
         System.out.println(str);
         
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(baos!=null)
            baos.close();
      }   
   }
}

輸出

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

ABCDE
java_bytearrayoutputstream.htm
廣告

© . All rights reserved.