Javas Temp File Facility

From WritingJavaUnitTests. Please explain what it is.


java.io.File.createTempFile(String prefix, String suffix) "Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name"


Something to be careful of is apps running on multi user environments (that would be non-windows operating systems then ;) in which two users create a tmp file of the same name. I avoided this by using the username in the tmp file names.

It was during unit tests that this problem actually occurred for me. They were fine when I developed them on MicrosoftWindows but when the automated tests ran on solaris, occasionally there would be bizarre failures caused by others running the tests too. Nasty to track down but easily solved. --ChanningWalton


What if the same user is logged on twice? Why not use System.currentTimeMillis() or Random.nextLong() to generate something more portable and with a greater chance of being unique?

On Unix, a common idiom is to use the ID of the process in the name of the temp file.

Yes even better. My (flawed) assumption was that only one instance of the app per user would be running - depends on the app really. --ChanningWalton

Anyone have an easy and portable way to get the current PID from within the JVM?


I don't think you need to worry about creating two temp files with the same name, even across processes. The JavaDoc states:

"Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that: 1. The file denoted by the returned abstract pathname did not exist before this method was invoked [...]" (http://java.sun.com/j2se/1.3/docs/api/java/io/File.html#createTempFile%28java.lang.String,%20java.lang.String,%20java.io.File%29)

Doesn't this imply that ensuring no two processes create the same file is the JVM's responsibility? --RodWaldhoff?


Not necessarily. It says if this method returns successfully, but it says nothing about what conditions may cause the documented IOException - If a file could not be created. A given implementation may attempt various transformations for uniqueness before giving up, but a program can't count on it always returning successfully. Defensive programming would suggest that the program calling createTempFile make an effort to ensure that the supplied filename base has an element of uniqueness built in. --StevenNewton


Fair enough, and I haven't looked at the implementing code (the important part is probably a native implementation anyway) but I've never run into that problem in practice, and I use this createTempFile approach rather often on a variety of platforms. Is anyone aware of a JRE that implements this naive approach? --RodWaldhoff?


EditText of this page (last edited January 26, 2007) or FindPage with title or text search