免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5550 | 回复: 0
打印 上一主题 下一主题

ByteArrayOutputStream的用法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-02-24 11:45 |只看该作者 |倒序浏览
ByteArrayOutputStream类是在创建它的实例时,程序内部创建一个byte型别数组的缓冲区,然后利用ByteArrayOutputStream和ByteArrayInputStream的实例向数组中写入或读出byte型数据。在网络传输中我们往往要传输很多变量,我们可以利用ByteArrayOutputStream把所有的变量收集到一起,然后一次性把数据发送出去。具体用法如下:
ByteArrayOutputStream:    可以捕获内存缓冲区的数据,转换成字节数组
ByteArrayInputStream: 可以将字节数组转化为输入流
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);
    System.out.println("***********************");
    ByteArrayInputStream bin = new ByteArrayInputStream(buff);
    while ((b = bin.read()) != -1) {
        System.out.println(b);
    }
}
如上所示,ByteArrayOutputStream把内存中的数据读到字节数组中,而ByteArrayInputStream又把字节数组中的字节以流的形式读出,实现了对同一个字节数组的操作.
综合DataOutputStream&DataInputStream的作用和功能,与ByteArrayOutputStream和ByteArrayInputSream使用将更方便.此时DataOutputStream&DataInputStream封闭了字节流,以适当的形式读出了字节数组中的数据.如下所示:
public static void main(String[] args) throws IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);
    String name = "xxy";
    int age = 84;
    dout.writeUTF(name);
    dout.writeInt(age);
    byte[] buff = bout.toByteArray();
    ByteArrayInputStream bin = new ByteArrayInputStream(buff);
    DataInputStream dis = new DataInputStream(bin);
    String newName = dis.readUTF();
    int newAge = dis.readInt();
    System.out.println(newName + ":" + newAge);
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/78343/showart_2185778.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP