java - FindBugs:解决 "Method ignores results of InputStream.skip()"的最佳方法是什么?

标签 java findbugs

我有以下代码:

final Response res = this.origin.act(req);
for (int count = req.body().available(); count > 0;
    count = req.body().available()) {
    body().skip(count);
}
return res;

FindBugs 在 body().skip(count) 中报告此问题:

FindBugs: L B RR: ignores result of java.io.InputStream.skip(long)

解决这个问题的最佳方法是什么?

谢谢

最佳答案

This method ignores the return value of java.io.InputStream.skip() which can skip multiple bytes. If the return value is not checked, the caller will not be able to correctly handle the case where fewer bytes were skipped than the caller requested. This is a particularly insidious kind of bug, because in many programs, skips from input streams usually do skip the full amount of data requested, causing the program to fail only sporadically. With Buffered streams, however, skip() will only skip data in the buffer, and will routinely fail to skip the requested number of bytes.

为了避免 findbugs 警告,以及忽略返回值可能掩盖的错误,您需要检查返回值是否与您请求跳过的数字匹配;例如

final Response res = this.origin.act(req);
for (int count = req.body().available(); count > 0;
    count = req.body().available()) {
    long skippedBytes = body().skip(count);
    if (skippedBytes != count) {
        // do something
    }
}
return res;

如果它们不匹配,您应该做的“某事”是您需要根据使用情况做出的选择;你可能想抛出异常,你可能想记录并继续,或者你可能想执行某种回退,等等

关于java - FindBugs:解决 "Method ignores results of InputStream.skip()"的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35914034/

相关文章:

java - 无法使用 for 循环添加空格分隔的输入

java - 不正确的逻辑

Java资源管理: understanding Findbugs results

javax.annotation.Nonnull 与断言

java - Sonar 不使用项目 pom.xml 中的 exceptFilterFile

java - Apache Camel XML 路由中的简单谓词不起作用 - 需要将 header 转换为字符串?

Java异常处理

java - 通用 Autowiring 不适用于@Transactional

findbugs - 在输出流中找到 'Reliance on default encoding'

java - 如何在 Java 中安全地写入静态字段?