ByteArrayOutputStream和ByteArrayInputStream詳解

ByteArrayOutputStream類是在創建它的實例時,程序內部創建一個byte型別數組的緩衝區,然後利用ByteArrayOutputStream和ByteArrayInputStream的實例向數組中寫入或讀出byte型數據。在網絡傳輸中我們往往要傳輸很多變量,我們可以利用ByteArrayOutputStream把所有的變量收集到一起,然後一次性把數據發送出去。具體用法如下:

ByteArrayOutputStream:    可以捕獲內存緩衝區的數據,轉換成字節數組。

ByteArrayInputStream: 可以將字節數組轉化爲輸入流

 

 1import java.io.*;
 2
 3public class test {
 4 public static void main(String[] args) {
 5  int a=0;
 6  int b=1;
 7  int c=2;
 8  ByteArrayOutputStream bout = new ByteArrayOutputStream();
 9  bout.write(a);
10  bout.write(b);
11  bout.write(c);
12  byte[] buff = bout.toByteArray();
13  for(int i=0; i<buff.length; i++)
14   System.out.println(buff[i]);
15  System.out.println("***********************");
16  ByteArrayInputStream bin = new ByteArrayInputStream(buff);
17  while((b=bin.read())!=-1{
18   System.out.println(b);
19  }

20 }

21}

22
23
24

如上所示,ByteArrayOutputStream把內存中的數據讀到字節數組中,而ByteArrayInputStream又把字節數組中的字節以流的形式讀出,實現了對同一個字節數組的操作.

綜合DataOutputStream&DataInputStream的作用和功能,與ByteArrayOutputStream和ByteArrayInputSream使用將更方便.此時DataOutputStream&DataInputStream封閉了字節流,以適當的形式讀出了字節數組中的數據.如下所示:

 1import java.io.*;
 2
 3public class test {
 4 public static void main(String[] args)throws IOException {
 5  ByteArrayOutputStream bout = new ByteArrayOutputStream();
 6  DataOutputStream dout = new DataOutputStream(bout);
 7  String name = "xxy";
 8  int age = 84;
 9  dout.writeUTF(name);
10  dout.writeInt(age);
11  byte[] buff = bout.toByteArray();
12  ByteArrayInputStream bin = new ByteArrayInputStream(buff);
13  DataInputStream dis = new DataInputStream(bin);
14  String newName = dis.readUTF();
15  int newAge = dis.readInt();
16  System.out.println(newName+":"+newAge);
17 }

18}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章