Jan*_*n B 5 java inputstream apache-commons apache-commons-io
我正在尝试从InputStream读取数据,该数据可以是FileInputStream或ObjectInputStream.为了实现这一点,我想克隆流并尝试读取Object,并在异常的情况下使用apache commons io将流转换为String.
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");
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用,因为程序在尝试将流转换in为String 时等待传入的数据.
正如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");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11936 次 |
| 最近记录: |