ByteArrayOutputStream類是在創建它的實例時,程序內部創建一個byte型別數組的緩沖區,
然后利用ByteArrayOutputStream和ByteArrayInputStream的實例向數組中寫入或讀出byte型數據。
在網絡傳輸中我們往往要傳輸很多變量,我們可以利用ByteArrayOutputStream把所有的變量收集到一起,然后一次性把數據發送出去。
具體用法如下:
ByteArrayOutputStream: 可以捕獲內存緩沖區的數據,轉換成字節數組 (從數組寫)
ByteArrayInputStream: 可以將字節數組轉化為輸入流 (從數組讀)
1 public static void main(String[] args) { 2 int a = 0; 3 int b = 1; 4 int c = 2; 5 ByteArrayOutputStream bout = new ByteArrayOutputStream(); 6 bout.write(a); 7 bout.write(b); 8 bout.write(c); 9 byte[] buff = bout.toByteArray(); 10 for (int i = 0; i < buff.length; i++) 11 System.out.println(buff[i]); 12 System.out.println("***********************"); 13 ByteArrayInputStream bin = new ByteArrayInputStream(buff); 14 while ((b = bin.read()) != -1) { 15 System.out.println(b); 16 } 17 }
如上所示,ByteArrayOutputStream把內存中的數據讀到字節數組中,而ByteArrayInputStream又把字節數組中的字節以流的形式讀出,實現了對同一個字節數組的操作.
綜合DataOutputStream&DataInputStream的作用和功能,與ByteArrayOutputStream和ByteArrayInputSream使用將更方便.此時DataOutputStream&DataInputStream封閉了字節流,以適當的形式讀出了字節數組中的數據.如下所示:
1 public static void main(String[] args) throws IOException { 2 ByteArrayOutputStream bout = new ByteArrayOutputStream(); 3 DataOutputStream dout = new DataOutputStream(bout); 4 String name = "xxy"; 5 int age = 84; 6 dout.writeUTF(name); 7 dout.writeInt(age); 8 byte[] buff = bout.toByteArray(); 9 ByteArrayInputStream bin = new ByteArrayInputStream(buff); 10 DataInputStream dis = new DataInputStream(bin); 11 String newName = dis.readUTF(); 12 int newAge = dis.readInt(); 13 System.out.println(newName + ":" + newAge); 14 }