克隆输入流

5
我正在尝试从一个InputStream中读取数据,这个流可以是FileInputStream或ObjectInputStream。为了实现这一点,我想克隆这个流并尝试读取对象,在出现异常的情况下使用Apache Commons IO将流转换成字符串。
    PipedInputStream in = new PipedInputStream();
    TeeInputStream tee = new TeeInputStream(stream, new PipedOutputStream(in));

    Object body;
    try {
        ObjectInput ois = new ObjectInputStream(tee);
        body = ois.readObject();
    } catch (Exception e) {
        try {
            body = IOUtils.toString(in, Charset.forName("UTF-8"));
        } catch (Exception e2) {
            throw new MarshallerException("Could not convert inputStream");
        }
    }

不幸的是,这种方法行不通,因为程序在尝试将流 in 转换为字符串时需要等待传入的数据。

2
不可以创建两个流,这是行不通的。但你可以将整个流读入到已知源(例如 byte[]File),然后在该源上打开新的流进行测试。你可以尝试使用 mark()reset(),但这取决于流的来源是否支持。 - Boris the Spider
根据https://dev59.com/m2ct5IYBdhLWcg3wa8w_,使用apache commons io的TeeInputStream和PipedInputStream应该可以实现。 - Jan B
1个回答

8

如Boris Spider所评论的那样,可以将整个流读取到字节数组流中,然后在该资源上打开新的流:

    byte[] byteArray = IOUtils.toByteArray(stream);     
    InputStream input1 = new ByteArrayInputStream(byteArray);
    InputStream input2 = new ByteArrayInputStream(byteArray);

    Object body;
    try {
        ObjectInput ois = new ObjectInputStream(input1);
        body = ois.readObject();
    } catch (Exception e) {
        try {
            body = IOUtils.toString(input2, Charset.forName("UTF-8"));
       } catch (Exception e2) {
            throw new MarshalException("Could not convert inputStream");
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接