Create a Temporary File in Java
Last Updated :
08 Nov, 2022
In Java, we can create a temporary file using an existing method known as File.createTempFile() method which creates a new empty file on the specified directory. The createTempFile() function creates a temporary file in a given directory (if the directory is not mentioned then a default directory is selected), the function generates the filename by using the prefix and suffix passed as the parameters. If the suffix is null then the function uses “.tmp” as suffix. The function then returns the created file
Scenarios: There are two scenarios in which we can create a Temporary File.
- createTempFile(prefix,suffix,directory)
- createTempFile(prefix,suffix,null)
Method — Scenario 1
This method creates a new and empty file in the specified directory, using the given prefix and suffix to generate its name.
Syntax:
public static File createTempFile(String prefix,String suffix,File directory)
Parameters: It takes 3 parameters- prefix, suffix, and the directory.
- Prefix: The prefix string is used in generating the file's name, must be at least three characters long.
- Suffix: The suffix string is used in generating the file's name.It can be '.txt' or 'null'.In case of 'null' ".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.
Return Type: An abstract pathname denoting a newly-created empty file
Exceptions:
- IllegalArgumentExpression: If prefix argument contains less than three characters.
- IOException: If a file could not be created.
- SecurityException: If a security manager exists and its SecurityManager and checkWrite() method does not allow a file to be created.
Method — Scenario 2
This method creates a new and 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).
Syntax:
public static File createTempFile(String prefix,String suffix)
Parameters: It only takes two parameters- prefix and suffix
- Prefix: The prefix string is used in generating the file's name,must be at least three characters long
- Suffix: The suffix string is used in generating the file's name.It can be '.txt' or 'null'.In case of 'null' ".tmp" will be used
Return Type: An abstract pathname denoting a newly-created empty file
Exceptions:
- IllegalArgumentExpression: If prefix argument contains less than three characters.
- IOException: If a file could not be created.
- SecurityException: If a security manager exists and its SecurityManager and checkWrite() method does not allow a file to be created.
Example
Java
// Java Program to Create a Temporary File in Java
// Importing all input output classes
import java.io.File;
import java.io.IOException;
// Class
public class GFG {
// Main driver method
public static void main(String[] args)
throws IOException
{
// Try block to check for exceptions
try {
// Step 1
// Creating temporary file with default location
// by creating an object of File type
File obj1 = File.createTempFile("temp", ".txt");
// Step 2
// Obtaining absolute path of the path
// returned by createTempfile() function
String path = obj1.getAbsolutePath();
// Step 3
// Print and display the default path of
// temporary file
System.out.println(
"Path of temporary file with default location:"
+ path);
// Step 4
// Creating temporary file with specified
// location again by creating another object of
// File type which is custom local directory
File obj2 = File.createTempFile(
"temp", ".txt",
new File(
"C:/Users/ASPIRE/Desktop/my folder"));
// Step 5
// Obtaining absolute path of the path
// returned by createTempfile() function
path = obj2.getAbsolutePath();
// Step 6
// Print and display the specified path of
// temporary file
System.out.println(
"Path of temporary file with specified location:"
+ path);
}
// Catch block to handle exception if occurs
catch (IOException e) {
// Print the line number where exception occur
// using printStackTrace() method
e.printStackTrace();
}
}
}
Output:

Below snapshots are also appended at these directories in a local computer which is as follows:
The case where the temporary file is created at the given path

The case where the temporary file is created at the default path

Similar Reads
How to Create a File in CMD Creating a file using Windows GUI is very easy, but did you know that you can also create files using Windows CMD? Now, this article will walk you through the steps to create a file using CMD, ensuring that you can efficiently manage your files directly from the command prompt.How to Create a File i
4 min read
Different Ways to Copy Files in Java There are mainly 3 ways to copy files using java language. They are as given below: Using File Stream (Naive method)Using FileChannel ClassUsing Files class. Note: There are many other methods like Apache Commons IO FileUtils but we are solely discussing copying files using java classes. Method 1: U
5 min read
What is a Temporary File? A Temporary file is a file that is produced to temporarily store information, either for interim usage by a program or for transfer to a permanent file once completed. Computer programs may generate it for several reasons, including when memory is insufficient for the tasks at hand, when working wit
4 min read
How to Create a Swap File on Linux? Linux Operating System has some different features that are unique and not present in any other major operating system like Windows. The Linux Memory Distribution is one of them. The Memory Space in Linux is designed in such a way that the efficiency of the Memory Management could be the best. The L
4 min read
How to Create a .exe File From a Java Program? In this article, we will learn how to create a .exe file from a Java program. Java is a platform-independent language, which works on the philosophy of "write Once, Run Anywhere". It simply means that if we write a Java program, we can run it on any device that has a JVM(Java Virtual Machine). Now i
5 min read
How to Check a File or Directory Exists in Java? One of the most frequent tasks carried out by a file system in an operating system is checking the existence of a directory or a file. In the form of library functions, most programming languages provide some level of file system accessibility. You will discover how to test an existing file or direc
1 min read
File canWrite() method in Java with examples The canWrite()function is a part of File class in Java . This function determines whether the program can write the file denoted by the abstract path name.The function returns true if the abstract file path exists and the application is allowed to write the file. Function signature: public boolean c
2 min read
File Permissions in Java Java provides a number of method calls to check and change the permission of a file, such as a read-only file can be changed to have permissions to write. File permissions are required to be changed when the user wants to restrict the operations permissible on a file. For example, file permission ca
3 min read
File renameTo() method in Java with examples The renameTo() method is a part of File class. The renameTo() function is used to rename the abstract path name of a File to a given path name. The function returns true if the file is renamed else returns false Function Signature: public boolean renameTo(File destination) Syntax: file.renameTo(File
2 min read
Delete a File Using Java Java provides methods to delete files programmatically. In contrast to normal delete operations in any operating system, files being deleted using the Java program are deleted permanently without being moved to the trash/recycle bin. Example: A basic program to delete the file from a static path.Jav
2 min read