首页 > 解决方案 > 如何正确读取具有多个内容的 InputStream

问题描述

public static void main(String[] args) throws Exception
{
    // Server sends 3 numbers to the client
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bos.write(1000);
    bos.write(2000);
    bos.write(3000);

    // Client receive the bytes
    final byte[] bytes = bos.toByteArray();

    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    System.out.println(bis.read());
    System.out.println(bis.read());
    System.out.println(bis.read());
}

上面的代码是中断的,因为bis.read() 返回了一个 0 到 255 范围内的 int

我怎样才能正确接收这些号码?我应该使用分隔符并继续阅读流直到找到它吗?如果是这样,如果我要发送多个文件怎么办,我认为如果分隔符作为单个字节它可以匹配文件中的某个位置并且也会中断。

标签: java

解决方案


为您的流使用装饰器!

你所要做的就是用java.io.ObjectOutputStream/ 和包装你的输出和输入流java.io.ObjectInputStreamwriteInt这些类支持通过对/的单个方法调用来写入和读取整数(一个 4 字节值)readInt

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(bos);
    os.writeInt(1000);
    os.writeInt(2000);
    os.writeInt(3000);
    os.close();

    // Client receive the bytes
    final byte[] bytes = bos.toByteArray();

    ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(bytes));
    System.out.println(is.readInt());
    System.out.println(is.readInt());
    System.out.println(is.readInt());

不要忘记关闭流。使用 try/finally 或 try-with-resources。


推荐阅读