Latest web development tutorials

Java ByteArrayOutputStream類

字節數組輸出流在內存中創建一個字節數組緩衝區,所有發送到輸出流的數據保存在該字節數組緩衝區中。 創建字節數組輸出流對像有以下幾種方式。

下面的構造方法創建一個32字節(默認大小)的緩衝區。

OutputStream bOut = new ByteArrayOutputStream();

另一個構造方法創建一個大小為n字節的緩衝區。

OutputStream bOut = new ByteArrayOutputStream(int a)

成功創建字節數組輸出流對像後,可以參見以下列表中的方法,對流進行寫操作或其他操作。

序號 方法描述
1 public void reset()
將此字節數組輸出流的count字段重置為零,從而丟棄輸出流中目前已累積的所有數據輸出。
2 public byte[] toByteArray()
創建一個新分配的字節數組。 數組的大小和當前輸出流的大小,內容是當前輸出流的拷貝。
3 public String toString()
將緩衝區的內容轉換為字符串,根據平台的默認字符編碼將字節轉換成字符。
4 public void write(int w)
將指定的字節寫入此字節數組輸出流。
5 public void write(byte []b, int of, int len)
將指定字節數組中從偏移量off開始的len個字節寫入此字節數組輸出流。
6 public void writeTo(OutputStream outSt)
將此字節數組輸出流的全部內容寫入到指定的輸出流參數中。

實例

下面的例子演示了ByteArrayInputStream 和ByteArrayOutputStream的使用:

import java.io.*;
public class ByteStreamTest {
   public static void main(String args[])throws IOException {
      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
      while( bOutput.size()!= 10 ) {
         // 获取用户输入
         bOutput.write(System.in.read()); 
      }
      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");
      for(int x= 0 ; x < b.length; x++) {
         // 打印字符
         System.out.print((char)b[x]  + "   "); 
      }
      System.out.println("   ");
      int c;
      ByteArrayOutputStream bInput = new ByteArrayOutputStream(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(); 
      }
   }
}

以上實例編譯運行結果如下:

asdfghjkly
Print the content
a   s   d   f   g   h   j   k   l   y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
Y