Java 教程
字節(jié)數(shù)組輸出流在內(nèi)存中創(chuàng)建一個字節(jié)數(shù)組緩沖區(qū),所有發(fā)送到輸出流的數(shù)據(jù)保存在該字節(jié)數(shù)組緩沖區(qū)中。創(chuàng)建字節(jié)數(shù)組輸出流對象有以下幾種方式。
下面的構(gòu)造方法創(chuàng)建一個32字節(jié)(默認大?。┑木彌_區(qū)。
OutputStream bOut = new ByteArrayOutputStream();
另一個構(gòu)造方法創(chuàng)建一個大小為n字節(jié)的緩沖區(qū)。
OutputStream bOut = new ByteArrayOutputStream(int a)
成功創(chuàng)建字節(jié)數(shù)組輸出流對象后,可以參見以下列表中的方法,對流進行寫操作或其他操作。
序號 | 方法描述 |
---|---|
1 |
public void reset() 將此字節(jié)數(shù)組輸出流的 count 字段重置為零,從而丟棄輸出流中目前已累積的所有數(shù)據(jù)輸出。 |
2 |
public byte[] toByteArray() 創(chuàng)建一個新分配的字節(jié)數(shù)組。數(shù)組的大小和當前輸出流的大小,內(nèi)容是當前輸出流的拷貝。 |
3 |
public String toString() 將緩沖區(qū)的內(nèi)容轉(zhuǎn)換為字符串,根據(jù)平臺的默認字符編碼將字節(jié)轉(zhuǎn)換成字符。 |
4 |
public void write(int w) ?將指定的字節(jié)寫入此字節(jié)數(shù)組輸出流。 |
5 |
public void write(byte []b, int off, int len) ?將指定字節(jié)數(shù)組中從偏移量 off 開始的 len 個字節(jié)寫入此字節(jié)數(shù)組輸出流。 |
6 |
public void writeTo(OutputStream outSt) 將此字節(jié)數(shù)組輸出流的全部內(nèi)容寫入到指定的輸出流參數(shù)中。 |
下面的例子演示了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(); } } }
以上實例編譯運行結(jié)果如下:
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