...
Code Block | ||
---|---|---|
| ||
class TempFile { public static void main(String[] args) throws IOException{ File f = File.createTempFile("tempnam",".tmp"); FileOutputStream fop = null; try { fop = new FileOutputStream(f); String str = "Data"; fop.write(str.getBytes()); fop.flush(); } finally { // Stream/file still open; file will // not be deleted on Windows systems f.deleteOnExit(); // Delete the file when the JVM terminates if (fop != null) { try { fop.close(); } catch (IOException x) { // Handle error } } } } } |
Compliant Solution (
...
DELETE_ON_CLOSE
)
This compliant solution creates a temporary file using several methods from Java's NIO.2 package (introduced in Java SE 7). It uses the createTempFile()
method, which creates an unpredictable name. (The actual method by which the name is created is implementation-defined and undocumented.) The file is opened using the try
-with-resources construct, which automatically closes the file regardless of whether an exception occurs. Finally, the file is opened with the Java SE 7 DELETE_ON_CLOSE
option, which removes the file automatically when it is closed.
...
Failure to remove temporary files before termination can result in information leakage and resource exhaustion.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO03-J | Medium | Probable | Medium | P8 | L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.FIO03.ATF CERT.FIO03.REMTMP | Avoid temporary files Remove temporary files before termination |
Related Guidelines
FIO21-C. Do not create temporary files in shared directories | |
VOID FIO19-CPP. Do not create temporary files in shared directories | |
Bibliography
[API 2014] |
|
Section 11.5, "Creating a Transient File" | |
Bug JDK- |
[SDN 2008] | Bug |
ID: 4171239 | |
...
...