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 off, 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;
      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();
      }
   }
}
以上實例編譯運行結果如下:
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

 Java 流(Stream)
 Java 流(Stream)