猿问

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();
            }
倚天杖
浏览 363回答 1
1回答

温温酱

要dataOutputStream.flush();在先,System.out.println(dataOutputStream.size());在后
随时随地看视频慕课网APP

相关分类

Java
我要回答