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

FindBugs: What is the best way to solve "Method ignores results of InputStream.skip()"?

我有以下代码:

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 警告,因此忽略 return 值的错误可能会被掩盖,您需要检查 return 值是否与您请求跳过的数字相匹配;例如

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;

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

@beresfordt 谢谢。我想我使用 ByteStreams.skipFully(req.body(), count);

找到了更好的解决方案
final Response res = this.origin.act(req);
for (int count = req.body().available(); count > 0;
    count = req.body().available()) {
    ByteStreams.skipFully(req.body(), count);
}
return res;