Java Temporary Files

If your Java program creates a temporary file on user’s device which never gets deleted … shame on you. Not only that most users won’t realize your program did so, you’re also consuming disk space behind their back.

It shouldn’t matter how small the file is. If you have a massive backyard on your house, you won’t like strangers dumping lolly wrappings on it right?

Java SE API encourages you to be polite when placing temporary files by supporting it out-of-the-box:

String randomString = UUID.randomUUID().toString();
File tempFile = File.createTempFile(randomString, null);

The temporary file will be placed under java.io.tmpdir directory. And to ensure the file is deleted when the program exits, all you have to do is:

tempFile.deleteOnExit();

Make sure you don’t forget to close any streams that read/writes to the file so no file locks got left behind when runtime tries to delete them.