我正在尝试从一个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
转换为字符串时需要等待传入的数据。
byte[]
或File
),然后在该源上打开新的流进行测试。你可以尝试使用mark()
和reset()
,但这取决于流的来源是否支持。 - Boris the Spider