Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1184826
  • 博文数量: 233
  • 博客积分: 6270
  • 博客等级: 准将
  • 技术积分: 1798
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-26 08:32
文章分类

全部博文(233)

文章存档

2011年(31)

2010年(202)

我的朋友

分类: Java

2010-11-22 11:46:44

【博主注】
寻找这两个类的初衷是为了找到一个合适方法来组建特定格式的网络数据包
 
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 支持的写入格式比较有限,仅支持byte,int, long等。

如果加入DataOutputStream,则可以支持更多的格式,用法如下:

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();
    DataOutputStream dos = new DataOutputStream(bos);

    dos.writeByte(0);

    dos.writeInt(0);


    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);
     }
}


阅读(873) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~