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類是在創(chuàng)建它的實例時,程序內部創(chuàng)建一個byte型別數組的緩沖區(qū),然后利用ByteArrayOutputStream和ByteArrayInputStream的實例向數組中寫入或讀出byte型數據。在網絡傳輸中我們往往要傳輸很多變量,我們可以利用ByteArrayOutputStream把所有的變量收集到一起,然后一次性把數據發(fā)送出去。具體用法如下:

          ByteArrayOutputStream:    可以捕獲內存緩沖區(qū)的數據,轉換成字節(jié)數組。

          ByteArrayInputStream: 可以將字節(jié)數組轉化為輸入流

           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把內存中的數據讀到字節(jié)數組中,而ByteArrayInputStream又把字節(jié)數組中的字節(jié)以流的形式讀出,實現了對同一個字節(jié)數組的操作.

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

           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 閱讀(19672) 評論(0)  編輯  收藏 所屬分類: java i/o


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


          網站導航:
           
          主站蜘蛛池模板: 镇远县| 晋城| 凤阳县| 宁远县| 沾化县| 青神县| 镶黄旗| 上犹县| 义马市| 梅州市| 阿坝县| 丹寨县| 同心县| 芷江| 时尚| 双流县| 平度市| 北票市| 正宁县| 许昌市| 池州市| 五河县| 赤城县| 河东区| 郁南县| 石景山区| 壤塘县| 淄博市| 澳门| 玉屏| 个旧市| 永修县| 文化| 福鼎市| 通江县| 尚志市| 民县| 上蔡县| 吴旗县| 平塘县| 荃湾区|