What is a safe way to create a Temp file in Java?

JavaTemporary Files

Java Problem Overview


I'm looking for a safe way to create a temp file in Java. By safe, I mean the following:

  • Name should be unique, even under potential race conditions (e.g. another Thread calls the same func at the same time, or another process runs this code simultaneously)
  • File should be private, even under potential race conditions (e.g. another user tries to chmod file at high rate)
  • I can tell it to delete the file, without me having to do a generic delete, and risk deleting the wrong file
  • Ideally, should ensure file is deleted, even if exception is thrown before I get the chance to
  • File should default to a sane location (e.g. the JVM specified tmp dir, defaulting to the system temp dir)

Java Solutions


Solution 1 - Java

Use File.createTempFile().

File tempFile = File.createTempFile("prefix-", "-suffix");
//File tempFile = File.createTempFile("MyAppName-", ".tmp");
tempFile.deleteOnExit();

Will create a file in the temp dir, like:

> prefix-6340763779352094442-suffix

Solution 2 - Java

Since Java 7 there is the new file API "NIO2" which contains new methods for creating temnp files and directories. See

e.g.

Path tempDir = Files.createTempDirectory("tempfiles");

or

Path tempFile = Files.createTempFile("tempfiles", ".tmp");

Security notice:

Important difference between File.createTempFile() and Files.createTempFile is also that the latter has more secure permission defaults.

> When no file attributes are specified, then the resulting file may > have more restrictive access permissions to files created by the > File.createTempFile(String,String,File) method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSRobertJamesView Question on Stackoverflow
Solution 1 - JavaStefanView Answer on Stackoverflow
Solution 2 - JavaTim BütheView Answer on Stackoverflow