V6128. Using a Closeable object after it was closed can lead to an exception.
The analyzer has detected a method call on an object that had already been closed using the close
method. This may result in an exception being thrown.
The example:
public void appendFileInformation(String path) throws IOException {
FileInputStream is = new FileInputStream(path);
// ....
is.close();
// ....
if (is.available() == 0) {
System.out.println("EOF");
}
// ....
}
The condition ensures that the file has been completely read. The check compares the number of remaining bytes to zero. However, since the close
method is called on the is
variable before, calling the available
method results in an IOException
with the message Stream Closed
. That is because the resources held by is
are already released.
Look at a proper implementation of appendFileInformation
:
public void appendFileInformation(String path) throws IOException {
try (FileInputStream is = new FileInputStream("out.txt")) {
// ....
if (is.available() == 0) {
System.out.println("EOF");
}
// ....
}
}
To ensure the method works correctly, consider using try-with-resources
. In this case:
- the resources held by the
is
object will be automatically released after thetry
block ends; - the object cannot be accessed outside the
try
block, which adds an extra layer of protection againstIOException
. - resources are properly released even if an exception occurs inside the
try
block.
This diagnostic is classified as: