Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Potential output resource leak

ID: java/output-resource-leakKind: problemSecurity severity: Severity: warningPrecision: highTags:   - quality   - reliability   - performance   - efficiency   - resources   - external/cwe/cwe-404   - external/cwe/cwe-772Query suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

A subclass ofWriter orOutputStream that is opened for writing but not properly closed later may cause a resource leak.

Recommendation

Ensure that the resource is always closed to avoid a resource leak. Note that, because of exceptions, it is safest to close a resource properly in afinally block. (However, this is unnecessary for subclasses ofCharArrayWriter,StringWriter andByteArrayOutputStream.)

For Java 7 or later, the recommended way to close resources that implementjava.lang.AutoCloseable is to declare them within atry-with-resources statement, so that they are closed implicitly.

Example

In the following example, the resourcebw is opened but not closed.

publicclassCloseWriter{publicstaticvoidmain(String[]args)throwsIOException{BufferedWriterbw=newBufferedWriter(newFileWriter("C:\\test.txt"));bw.write("Hello world!");// ...}}

In the following example, the resourcebw is opened in atry block and later closed in afinally block.

publicclassCloseWriterFix{publicstaticvoidmain(String[]args)throwsIOException{BufferedWriterbw=null;try{bw=newBufferedWriter(newFileWriter("C:\\test.txt"));bw.write("Hello world!");}finally{if(bw!=null)bw.close();// 'bw' is closed}// ...}}

Note that nested class instance creation expressions ofWriters orOutputStreams are not safe to use if the constructor of the outer expression may throw an exception. In the following example, theOutputStreamWriter may throw an exception, in which case the innerFileOutputStream is not closed.

publicclassCloseWriterNested{publicstaticvoidmain(String[]args)throwsIOException{OutputStreamWriterwriter=null;try{// OutputStreamWriter may throw an exception, in which case the ...writer=newOutputStreamWriter(// ... FileOutputStream is not closed by the finally blocknewFileOutputStream("C:\\test.txt"),"UTF-8");writer.write("Hello world!");}finally{if(writer!=null)writer.close();}}}

In this case, the inner expression needs to be assigned to a local variable and closed separately, as shown below.

publicclassCloseWriterNestedFix{publicstaticvoidmain(String[]args)throwsIOException{FileOutputStreamfos=null;OutputStreamWriterwriter=null;try{fos=newFileOutputStream("C:\\test.txt");writer=newOutputStreamWriter(fos);writer.write("Hello world!");}finally{if(writer!=null)writer.close();// 'writer' is closedif(fos!=null)fos.close();// 'fos' is closed}}}

References


[8]ページ先頭

©2009-2025 Movatter.jp