How to Create Temporary File in Java
In some cases, you may need to create a temporary file in Java. It will often happen during unit tests when the results are not necessary to be stored. Immediately after the test is finished, you don’t need to worry about the content of the file.
Here, in this article, we are going to learn the ways of how to create temporary files in Java. There are two static methods named createTempFile in the Java File class, one that takes two arguments, and another that takes three arguments. It will help us to create a temporary file on the default temporary folder location. Another one is used to create temp file on the specified folder location.
Use File.createTempFile(String prefix, String suffix) method
Formal Syntax
public static File createTempFile(String prefix, String suffix)
This is an easy way to create a temporary file in operating system temporary directory.
This method creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to invoking createTempFile(prefix, suffix, null).
It returns an abstract pathname denoting a freshly-created empty file.
This method has the following parameters:
- prefix - The prefix string to be used in generating the file's name; must be at least three characters long.
- suffix - The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used.
Example
import java.io.File;
import java.io.IOException;
public class JavaTempFile {
public static void main(String[] args) {
try {
File tmpFile = File.createTempFile("data", null);
File newFile = File.createTempFile("text", ".temp", new File("/Users/name/temp"));
System.out.println(tmpFile.getCanonicalPath());
System.out.println(newFile.getCanonicalPath());
// write,read data to temporary file like any normal file
// delete when application terminates
tmpFile.deleteOnExit();
newFile.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output for the above code file will be:
Result
/private/var/folders/1t/sx2jbcl534z88byy78_36ykr0000gn/T/data225458400489752329.tmp
/Users/name/temp/text2548249124983543974.temp
Use File.createTempFile(String prefix, String suffix, File directory) method
Formal Syntax
public static File createTempFile(String prefix, String suffix, File directory)
This method creates a new empty file in the specified temporary file directory, using the provided prefix and suffix to produce its name.
The prefix argument must be at least three characters long. It is recommended that the prefix be a short, meaningful string such as "ffn" 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 also 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.
This method has the following parameters:
- prefix - The prefix string to be used in generating the file's name; must be at least three characters long.
- suffix - The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used.
- directory - The directory in which the file is to be created, or null if the default temporary-file directory is to be used.
This method returns an abstract pathname indicating a lately-created empty file. It throws an IOException, if the file could not be created, a IllegalArgumentException, if the prefix argument contains fewer than three characters and a SecurityException, if a security manager exists and its java.lang.SecurityManager.checkWrite(java.lang.String) method does not allow a file to be created.
Now, let’s see the above-mentioned method in use:
Example
import java.io.File;
import java.io.IOException;
public class TempFileExample {
public static void main(String[] args) {
try {
File tempFile = File.createTempFile("hello", ".tmp");
System.out.println("Temp file On Default Location: " + tempFile.getAbsolutePath());
tempFile = File.createTempFile("hello", ".tmp", new File("C:/"));
System.out.println("Temp file On Specified Location: " + tempFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
The output for this will be the following:
Result
Temp file On Default Location: C:\Users\swami\AppData\Local\Temp\hello7828748332363277400.tmp
Temp file On Specified Location: C:\hello950036450024130433.tmp
As a conclusion here see some notes regarding the Java File class temporary files:
- Call the deleteOnExit() method with the three-argument version of the createTempFile() method to get rid of the temporary file automatically
- Regarding the deleteOnExit() Javadoc provides the information that deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification.