...
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.
...
[API 2014] |
| |
Section 11.5, "Creating a Transient File" | ||
| ||
[SDN 2008] | Bug | JDK-4631820ID: 4171239 |
...