- 論壇徽章:
- 0
|
ByteArrayOutputStream類是在創(chuàng)建它的實例時,程序內(nèi)部創(chuàng)建一個byte型別數(shù)組的緩沖區(qū),然后利用ByteArrayOutputStream和ByteArrayInputStream的實例向數(shù)組中寫入或讀出byte型數(shù)據(jù)。在網(wǎng)絡(luò)傳輸中我們往往要傳輸很多變量,我們可以利用ByteArrayOutputStream把所有的變量收集到一起,然后一次性把數(shù)據(jù)發(fā)送出去。具體用法如下:
ByteArrayOutputStream: 可以捕獲內(nèi)存緩沖區(qū)的數(shù)據(jù),轉(zhuǎn)換成字節(jié)數(shù)組
ByteArrayInputStream: 可以將字節(jié)數(shù)組轉(zhuǎn)化為輸入流
public static void main(String[] args) {
int a = 0;
int b = 1;
int c = 2;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
bout.write(a);
bout.write(b);
bout.write(c);
byte[] buff = bout.toByteArray();
for (int i = 0; i buff.length; i++)
System.out.println(buff);
System.out.println("***********************");
ByteArrayInputStream bin = new ByteArrayInputStream(buff);
while ((b = bin.read()) != -1) {
System.out.println(b);
}
}
如上所示,ByteArrayOutputStream把內(nèi)存中的數(shù)據(jù)讀到字節(jié)數(shù)組中,而ByteArrayInputStream又把字節(jié)數(shù)組中的字節(jié)以流的形式讀出,實現(xiàn)了對同一個字節(jié)數(shù)組的操作.
綜合DataOutputStream&DataInputStream的作用和功能,與ByteArrayOutputStream和ByteArrayInputSream使用將更方便.此時DataOutputStream&DataInputStream封閉了字節(jié)流,以適當(dāng)?shù)男问阶x出了字節(jié)數(shù)組中的數(shù)據(jù).如下所示:
public static void main(String[] args) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
String name = "xxy";
int age = 84;
dout.writeUTF(name);
dout.writeInt(age);
byte[] buff = bout.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(buff);
DataInputStream dis = new DataInputStream(bin);
String newName = dis.readUTF();
int newAge = dis.readInt();
System.out.println(newName + ":" + newAge);
}
本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u2/78343/showart_2185778.html |
|