letter Y A N. G Brass Letter F a n-spo D Pewter Uppercase Letter I N G
          隨筆 - 4, 文章 - 10, 評論 - 2, 引用 - 0
          數據加載中……

          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}

          posted on 2008-10-01 23:39 rainman 閱讀(19670) 評論(0)  編輯  收藏 所屬分類: java i/o


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 渭源县| 双柏县| 牡丹江市| 泸水县| 塔河县| 大城县| 云安县| 水富县| 永定县| 周宁县| 孝感市| 蒙山县| 石渠县| 雅安市| 和平县| 马山县| 沂水县| 长兴县| 嘉鱼县| 神池县| 礼泉县| 海口市| 蚌埠市| 拜城县| 岐山县| 荔波县| 奉贤区| 娱乐| 宜宾县| 武安市| 龙山县| 台南县| 农安县| 册亨县| 葵青区| 托克托县| 郁南县| 富顺县| 金秀| 河北省| 太湖县|