Connections, streams, files, and other classes that implement the Closeable interface or its super-interface,AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwisean exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using"try-with-resources" pattern and will be closed automatically.
Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box the applicationis on to their knees.
Noncompliant Code Example
private void readTheFile() throws IOException { Path path = Paths.get(this.fileName); BufferedReader reader = Files.newBufferedReader(path, this.charset); // ... reader.close(); // Noncompliant // ... Files.lines("input.txt").forEach(System.out::println); // Noncompliant: The stream needs to be closed}private void doSomething() { OutputStream stream = null; try { for (String property : propertyList) { stream = new FileOutputStream("myfile.txt"); // Noncompliant // ... } } catch (Exception e) { // ... } finally { stream.close(); // Multiple streams were opened. Only the last is closed. }}
Instances of the following classes are ignored by this rule because close has no effect:
java.io.ByteArrayOutputStream
java.io.ByteArrayInputStream
java.io.CharArrayReader
java.io.CharArrayWriter
java.io.StringReader
java.io.StringWriter
Java 7 introduced the try-with-resources statement, which implicitly closes Closeables. All resources opened in a try-with-resourcesstatement are ignored by this rule.
Connections, streams, files, and other classes that implement the
Closeable
interface or its super-interface,AutoCloseable
, needs to be closed after use. Further, thatclose
call must be made in afinally
block otherwisean exception could keep the call from being made. Preferably, when class implementsAutoCloseable
, resource should be created using"try-with-resources" pattern and will be closed automatically.Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box the applicationis on to their knees.
Noncompliant Code Example
Compliant Solution
Exceptions
Instances of the following classes are ignored by this rule because
close
has no effect:java.io.ByteArrayOutputStream
java.io.ByteArrayInputStream
java.io.CharArrayReader
java.io.CharArrayWriter
java.io.StringReader
java.io.StringWriter
Java 7 introduced the try-with-resources statement, which implicitly closes
Closeables
. All resources opened in a try-with-resourcesstatement are ignored by this rule.See
File Path: webgoat-lessons/jwt/src/main/java/org/owasp/webgoat/jwt/JWTFinalEndpoint.java:167
Mitigation: Use try-with-resources or close this "Statement" in a "finally" clause.
https://preprod.armorcode.ai/#/findings/5407956