W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
字節(jié)數(shù)組輸出流在內(nèi)存中創(chuàng)建一個(gè)字節(jié)數(shù)組緩沖區(qū),所有發(fā)送到輸出流的數(shù)據(jù)保存在該字節(jié)數(shù)組緩沖區(qū)中。創(chuàng)建字節(jié)數(shù)組輸出流對(duì)象有以下幾種方式。
下面的構(gòu)造方法創(chuàng)建一個(gè)32字節(jié)(默認(rèn)大?。┑木彌_區(qū)。
OutputStream bOut = new ByteArrayOutputStream();
另一個(gè)構(gòu)造方法創(chuàng)建一個(gè)大小為n字節(jié)的緩沖區(qū)。
OutputStream bOut = new ByteArrayOutputStream(int a)
成功創(chuàng)建字節(jié)數(shù)組輸出流對(duì)象后,可以參見(jiàn)以下列表中的方法,對(duì)流進(jìn)行寫(xiě)操作或其他操作。
序號(hào) | 方法描述 |
---|---|
1 | public void reset() 將此字節(jié)數(shù)組輸出流的 count 字段重置為零,從而丟棄輸出流中目前已累積的所有數(shù)據(jù)輸出。 |
2 | public byte[] toByteArray() 創(chuàng)建一個(gè)新分配的字節(jié)數(shù)組。數(shù)組的大小和當(dāng)前輸出流的大小,內(nèi)容是當(dāng)前輸出流的拷貝。 |
3 | public String toString() 將緩沖區(qū)的內(nèi)容轉(zhuǎn)換為字符串,根據(jù)平臺(tái)的默認(rèn)字符編碼將字節(jié)轉(zhuǎn)換成字符。 |
4 | public void write(int w) 將指定的字節(jié)寫(xiě)入此字節(jié)數(shù)組輸出流。 |
5 | public void write(byte []b, int of, int len) 將指定字節(jié)數(shù)組中從偏移量 off 開(kāi)始的 len 個(gè)字節(jié)寫(xiě)入此字節(jié)數(shù)組輸出流。 |
6 | public void writeTo(OutputStream outSt) 將此字節(jié)數(shù)組輸出流的全部?jī)?nèi)容寫(xiě)入到指定的輸出流參數(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 ) { // 獲取用戶(hù)輸入 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(); } } }
以上實(shí)例編譯運(yùn)行結(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
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: