Java - ByteArrayOutputStream



Java ByteArrayOutputStream 類實現了一個輸出流,其中資料寫入到一個位元組陣列中。緩衝區會隨著資料的寫入自動增長。以下是關於 ByteArrayOutputStream 的重要要點:

  • 關閉 ByteArrayOutputStream 沒有任何效果。

  • 在流關閉後,仍然可以呼叫此類中的方法,而不會產生 IOException。

類宣告

以下是 Java.io.ByteArrayOutputStream 類的宣告:

public class ByteArrayOutputStream
   extends OutputStream

欄位

以下是 Java.io.ByteArrayOutputStream 類的欄位:

  • protected byte[] buf - 這是儲存資料的緩衝區。

  • protected int count - 這是緩衝區中有效位元組的數量。

類建構函式

序號 建構函式及說明
1

ByteArrayOutputStream()

建立一個新的位元組陣列輸出流。

2

ByteArrayOutputStream(int size)

建立一個新的位元組陣列輸出流,緩衝區容量為指定的位元組數。

類方法

序號 方法及說明
1 void close()

關閉 ByteArrayOutputStream 沒有任何效果。

2 void reset()

此方法將此位元組陣列輸出流的 count 欄位重置為零,從而丟棄輸出流中當前累積的所有輸出。

3 int size()

此方法返回緩衝區的當前大小。

4 byte[] toByteArray()

此方法建立一個新分配的位元組陣列。

5 String toString()

此方法將緩衝區的內容轉換為字串,使用平臺的預設字元集解碼位元組。

6 String toString(String charsetName)

此方法將緩衝區的內容轉換為字串,使用指定的 charsetName 解碼位元組。

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

此方法將指定位元組陣列中從偏移量 off 開始的 len 個位元組寫入此位元組陣列輸出流。

8 void write(int b)

此方法將指定的位元組寫入此位元組陣列輸出流。

9 void writeTo(OutputStream out)

此方法將此位元組陣列輸出流的完整內容寫入指定的輸出流引數,就像透過使用 out.write(buf, 0, count) 呼叫輸出流的 write 方法一樣。

繼承的方法

此類繼承自以下類的方法:

  • Java.io.OutputStream
  • Java.io.Object

示例

以下是一個演示 ByteArrayOutputStream 和 ByteArrayInputStream 的示例。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteStreamTest {
   public static void main(String args[])throws IOException {
      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);

      while( bOutput.size()!= 10 ) {
         // Gets the inputs from the user
         bOutput.write("hello".getBytes());  
      }
      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");
      
      for(int x = 0; x < b.length; x++) {
         // printing the characters
         System.out.print((char)b[x]  + "   "); 
      }
      System.out.println("   ");

      int c;
      ByteArrayInputStream bInput = new ByteArrayInputStream(b);
      System.out.println("Converting characters to Upper case " );
      
      for(int y = 0 ; y < 1; y++ ) {
         while(( c = bInput.read())!= -1) {
            System.out.println(Character.toUpperCase((char)c));
         }
         bInput.reset(); 
      }
   }
}

以下是上述程式的示例執行結果:

輸出

Print the content
h   e   l   l   o   h   e   l   l   o      
Converting characters to Upper case 
H
E
L
L
O
H
E
L
L
O
java_files_io.htm
廣告