H5W3
当前位置:H5W3 > 其他技术问题 > 正文

IO之BufferedOutputStream

当使用BufferedOutputStream为其做缓冲的时候,dataOutputStream对象的size为0,而不使用BufferedOutputStream做缓冲时,dataOutputStream值获取正常?

String string = "数据类型";
        double d = 2.3;
        long p = 10L;
        byte[] byteArray = null;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
      **//DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(bout));**
        DataOutputStream dataOutputStream = new DataOutputStream(bout);
        try {
            dataOutputStream.writeUTF(string);
            dataOutputStream.writeLong(p);
            dataOutputStream.writeDouble(d);
            **System.out.println(dataOutputStream.size());**
            byteArray = bout.toByteArray();
            dataOutputStream.flush();
            dataOutputStream.close();
            bout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

为什么这样可以:

DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(bs)));
            try {
                System.out.println(dataInputStream.readUTF());
                System.out.println(dataInputStream.readLong());
                System.out.println(dataInputStream.readDouble());
            } catch (IOException e) {
                e.printStackTrace();
            }

回答:

dataOutputStream.flush();在先,System.out.println(dataOutputStream.size());在后

本文地址:H5W3 » IO之BufferedOutputStream

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址