返回信息流现有一个InputStream。问题如下:
0. 我的目的是把它读到一个byte[]数组中。即IOUtils.toByteArray(is)
1. InputStream长度未知。我需要限制于1048576字节便不再读取。(单独这个功能可以用org.apache.commons.io.input.BoundedInputStream做到。)
2. 读InputStream的时候可能会抓到IOException。我希望在出错的时候,忽略错误,认为读取结束。(单独这个功能我还不知道哪个类能做到。用IOUtils.toByteArray,如果有IOException,整个读取过程就失败,什么也不会返回。)
有没有合适的方法实现这个,类似这样?
byte[] result = IOUtils.toByteArray(
new BoundedInputStream(
new SomeMysteriousWrapperThatAutomaticallyIgnoresIOExceptions(
myInputStream
)
), 1048576
);
或者
byte[] result = SomeUtils.readAsMuchAsPossibleLimitSizeAndIgnoreIOExceptions(myInputStream, 1048576);
这是一条镜像帖。来源:北邮人论坛 / java / #17716同步于 2011/3/28
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
Commons-IO能不能有限读取,忽略错误?
wks
2011/3/28镜像同步4 回复
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
"正常读取"部分不想自己做,最好给IOUtils.toByteArray做。
希望catch到exception的时候,能留住已经读的部分,而不是扔掉。
其实早些时候我已经重新发明了这么一个轮子,就是这种try{...}catch{...}的方法,里面用read(buf,offset,size)读。但是,只要输入稍微变化一下(比如要保留InputStream接口,或者从InputStream拷贝到OutputStream),就不行了。
【 在 fykhlp 的大作中提到: 】
: try
: {
: //正常读取
: ...................
最后用这么个玩意儿解决了:
class TheMysteriousWrapperThatAutomaticallyIgnoresIOExceptions extends FilterInputStream {
private Exception exception = null;
public Exception getException() { return exception; }
// 必须套在另一个InputStream上用
public TheMysteriousWrapperThatAutomaticallyIgnoresIOExceptions(InputStream in) { this.in = in; }
@Override public int read() {
if (exception!=null) return -1; // 只要有异常就假装到了EOF
try {
return in.read(); // 没异常就正常读。
} catch (Exception e) {
exception = e;
return -1;
}
}
}
学习了~
【 在 wks 的大作中提到: 】
: 最后用这么个玩意儿解决了:
: class TheMysteriousWrapperThatAutomaticallyIgnoresIOExceptions extends FilterInputStream {
: private Exception exception = null;
: ...................