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为字符串时等待传入数据。

4

1 回答 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");
        }
    }
于 2014-06-29T10:36:55.757 回答