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 directory. And to ensure the file is deleted when the program exits, all you have to do is:


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.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s