Java 克隆输入流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24471089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:23:35  来源:igfitidea点击:

Clone InputStream

javainputstreamapache-commonsapache-commons-io

提问by Jan B

I'm trying to read data from an InputStream, which could either be a FileInputStream or an ObjectInputStream. In order to achieve this I'wanted to clone the stream and try to read the Object and in case of an exception convert the stream to a String using apache commons io.

我正在尝试从 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");
        }
    }

Unfortunately this does not work as the program waits for incoming data when trying to convert the stream into a String.

不幸的是,这不起作用,因为程序在尝试将流转换in为字符串时等待传入的数据。

采纳答案by Jan B

As already commented by Boris Spider, it is possible to read the whole stream e.g. to a byte array stream and then open new streams on that resource:

正如 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");
        }
    }