You cannot assume that any given stream reading call will fill the byte[]
passed in to the method. Instead, you must check the value
returned by the read method to see how many bytes were read. Fail to do so, and you introduce bug that is both harmful and difficult to reproduce.
Similarly, you cannot assume that InputStream.skip
will actually skip the requested number of bytes, but must check the value returned
from the method.
This rule raises an issue when an InputStream.read
method that accepts a byte[]
is called, but the return value is not
checked, and when the return value of InputStream.skip
is not checked. The rule also applies to InputStream
child
classes.
Noncompliant code example
public void doSomething(String fileName) {
try {
InputStream is = new InputStream(file);
byte [] buffer = new byte[1000];
is.read(buffer); // Noncompliant
// ...
} catch (IOException e) { ... }
}
Compliant solution
public void doSomething(String fileName) {
try {
InputStream is = new InputStream(file);
byte [] buffer = new byte[1000];
int count = 0;
while (count = is.read(buffer) > 0) {
// ...
}
} catch (IOException e) { ... }
}