Apache POI 5.4.0 peekFirstNBytes与Commons IO 2.14.0兼容问题咨询
适配Commons IO 2.14.0的代码修改方案
问题核心在于Apache POI 5.4.0的这段代码依赖了Commons IO 2.15.0及以上版本才引入的BoundedInputStream.Builder API,而2.14.0版本仅支持传统构造方法。直接替换为以下代码即可解决编译错误:
copy(new BoundedInputStream(stream, limit), bos);
关键说明:
- Commons IO 2.14.0的
BoundedInputStream提供了BoundedInputStream(InputStream in, long size)构造方法,直接传入原始流和限制字节数,就能实现和Builder模式相同的"最多读取limit字节"的效果。 - 原代码中的强制类型转换
(OutputStream)bos可以省略,因为bos本身就是OutputStream类型,编译器能自动匹配方法参数。
可选扩展(如需控制流关闭行为):
如果需要避免BoundedInputStream关闭原始输入流(Builder模式默认会传递close调用,和构造方法默认行为一致),可以手动调用setPropagateClose方法:
BoundedInputStream boundedStream = new BoundedInputStream(stream, limit); boundedStream.setPropagateClose(false); // 关闭boundedStream时不关闭原始stream copy(boundedStream, bos);
内容的提问来源于stack exchange,提问作者编程界的吴世勋
相关产品推荐
相关产品推荐

