Delete Temporary Files on Exit

Sometimes your application requires holding data in a temporary file. I’ve had to do this when printing a PDF file. The following bit of code demonstrates how to create a temporary file and delete said file when the program terminates.

File temp = File.createTempFile("SomePrefix", ".pdf");
temp.deleteOnExit();

The file is created in the system’s temp directory, see the Java java.io.tmpdir property.


Leave a Reply