Real'sHowTo AddThis Feed Button
Custom Search

Create a temporary fileTag(s): IO


import java.io.File;

...

File temp = File.createTempFile("real",".howto");
temp.deleteOnExit();
Creates an empty file in the default temporary-file directory, using the given prefix ("real") and suffix (".howto"). Plus, the temporary file will be deleted when the virtual machine terminates. Deletion will be attempted only for normal termination of the virtual machine.

(Javadoc) The prefix argument must be at least three characters long. It is recommended that the prefix be a short, meaningful string such as "hjb" or "mail". The suffix argument may be null, in which case the suffix ".tmp" will be used. To create the new file, the prefix and the suffix may first be adjusted to fit the limitations of the underlying platform.

If the prefix is too long then it will be truncated, but its first three characters will always be preserved. If the suffix is too long then it too will be truncated, but if it begins with a period character ('.') then the period and the first three characters following it will always be preserved.

Once these adjustments have been made the name of the new file will be generated by concatenating the prefix, five or more internally-generated characters, and the suffix.


The location of the directory used to hold temporary files is defined by the property java.io.tmpdir. The default value can be changed with the command line used to launch the JVM :

java -Djava.io.tmpdir=C:\mydir  myClass
or , on Windows, you can set the environment variable TMP to a different value.

On some plateform, the temporary directory returned by java.io.tmpdir do not include a trailing slash. That is,

Win NT  --> C:\TEMP\
Win XP  --> C:\TEMP
Solaris --> /var/tmp/
Linux   --> /var/tmp
It's not a bad idea to check if there is a trailing slash or not.
String tempdir = System.getProperty("java.io.tmpdir");

if ( !(tempdir.endsWith("/") || tempdir.endsWith("\\")) )
   tempdir = tempdir + System.getProperty("file.separator");

blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]