ByteArrayOutputStream類是在創建它的實例時,程序內部創建一個byte型別數組的緩沖區,然后利用ByteArrayOutputStream和ByteArrayInputStream的實例向數組中寫入或讀出byte型數據。在網絡傳輸中我們往往要傳輸很多變量,我們可以利用ByteArrayOutputStream把所有的變量收集到一起,然后一次性把數據發送出去。具體用法如下:
ByteArrayOutputStream: 可以捕獲內存緩沖區的數據,轉換成字節數組。
ByteArrayInputStream: 可以將字節數組轉化為輸入流
import java.io.*;
public class test {
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[i]);
System.out.println("***********************");
ByteArrayInputStream bin = new ByteArrayInputStream(buff);
while((b=bin.read())!=-1) {
System.out.println(b);
}
}
}
如上所示,ByteArrayOutputStream把內存中的數據讀到字節數組中,而ByteArrayInputStream又把字節數組中的字節以流的形式讀出,實現了對同一個字節數組的操作.
綜合DataOutputStream&DataInputStream的作用和功能,與ByteArrayOutputStream和ByteArrayInputSream使用將更方便.此時DataOutputStream&DataInputStream封閉了字節流,以適當的形式讀出了字節數組中的數據.如下所示:
import java.io.*;
public class test {
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);
}
}
