游戏开发论坛

 找回密码
 立即注册
搜索
查看: 3315|回复: 0

对IO流的困惑~~ 望高手赐教! 先谢了!

[复制链接]

2

主题

7

帖子

7

积分

新手上路

Rank: 1

积分
7
发表于 2007-11-10 11:44:00 | 显示全部楼层 |阅读模式
问题:一个IO流不能被重复使用?每次数据改变都要重新创建?

相关代码:
import java.io.*;

public class Test{

  public static void main(String args[]){
      Test t = new Test();
      try{
          t.print();
      }catch(IOException e){
          e.printStackTrace();
      }
  }

  public void print()throws IOException{
      // 创建输出流
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      DataOutputStream dos = new DataOutputStream(baos);

      // 写入
      dos.writeUTF("Hello");
   
      // 创建输入流
      byte[] data = baos.toByteArray();
      ByteArrayInputStream bais = new ByteArrayInputStream(data);
      DataInputStream dis = new DataInputStream(bais);

      // 读取
      String str = dis.readUTF();
      System.out.println("message1:"+str); // 这里能读到是"Hello"

      //再次调用
      dos.writeUTF("World");

      data = baos.toByteArray();
      // 把data打印出来看看
      String s = new String(data);
      System.out.println("data:"+s);    // 是"Hello World"

      // 读出流
      str = dis.readUTF();
      System.out.println("message2:"+str); // 这里会报错
   
      /*把 读出流 的代码改为:
      dis = new DataInputStream(new ByteArrayInputStream(data));
      str = dis.readUTF();
      str += dis.readUTF();
      System.out.println("message2:"+str);
      可以正常读取
      */
   
      baos.close();
      dos.close();
      bais.close();
      dis.close();
    }
}

*********************************************
为什么啊?

数据不是被存到ByteArrayOutputStream的内部缓冲数组了吗?
打印出的data正好说明这点。

输出流每次读取后不是会记录下标的吗?但为什么读不出来?

那位能详细讲讲,谢了!

email : joopererer@yahoo.com.cn

[em4]
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2025-6-18 21:44

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表