ByteArrayOutputStream
類流在內存中創建緩衝區,並且發送到流的所有數據都存儲在緩衝區中。
以下是ByteArrayOutputStream
類提供的構造函數列表。
編號 | 構造函數 | 描述 |
---|---|---|
1 | ByteArrayOutputStream() |
此構造函數創建一個具有32 位元組緩衝區的ByteArrayOutputStream 對象。 |
2 | ByteArrayOutputStream(int a) |
此構造函數創建一個具有給定大小的緩衝區的ByteArrayOutputStream 對象。 |
當創建了ByteArrayOutputStream
對象,就可以使用它的輔助方法來寫入流或在流上執行其他操作。
編號 | 方法 | 描述 |
---|---|---|
1 | public void reset() |
此方法將位元組數組輸出流的有效位元組數重置為零,因此將丟棄流中的所有累積輸出。 |
2 | public byte[] toByteArray() |
此方法創建新分配的Byte 數組。 它的大小將是輸出流的當前大小,緩衝區的內容將被複製到其中。並以位元組數組的形式返回輸出流的當前內容。 |
3 | public String toString() |
將緩衝區內容轉換為字串。轉換將根據默認字元編碼完成。它返回從緩衝區內容轉換的String 類型數據。 |
4 | public void write(int w) |
將指定的數組寫入輸出流。 |
5 | public void write(byte []b, int of, int len) |
將從偏移量off 開始的len 個位元組數寫入流。 |
6 | public void writeTo(OutputStream outSt) |
將此Stream 的全部內容寫入指定的流參數。 |
示例
以將演示如何使用ByteArrayOutputStream
和ByteArrayInputStream
。
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("hello".getBytes());
}
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();
}
}
}
執行上面示例代碼,得到以下結果 -
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中方法重載和方法重寫的區別
下一篇:無