In this short article, you'll learn how to create a temporary file in Java using both NIO API and the legacy I/O API.
Using Files.createTempFile()
Method
In Java 7 and higher, you can use the Files.createTempFile()
static method from Java NIO Java to create a temporary file. This method creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
Here is an example:
try {
// create temporary file
Path path = Files.createTempFile("file-", ".tmp");
// print path
System.out.println(path.toAbsolutePath().toString());
} catch (IOException ex) {
ex.printStackTrace();
}
The above code will create a temporary file and print its absolute path on the console. Here is how it looks like on a Linux machine:
/tmp/file-5451298069416200317.tmp
To create a temporary file in another folder, you can use pass an instance of Path
as a first argument to Files.createTempFile()
method as shown below:
try {
// folder to create temporary file
Path folder = Paths.get("dir");
// create temporary file
Path path = Files.createTempFile(folder, "file-", ".tmp");
// print path
System.out.println(path.toAbsolutePath().toString());
} catch (IOException ex) {
ex.printStackTrace();
}
Using File.createTempFile()
Method
Another way to create a temporary file in Java is by using the legacy I/O API File.createTempFile()
method. It works almost similar to the above method (create a temporary file in the default temporary-file folder):
try {
// create temporary file
File file = File.createTempFile("file-", ".tmp");
// print path
System.out.println(file.getAbsolutePath());
} catch (IOException ex) {
ex.printStackTrace();
}
You can even explicitly specify the directory path to create a temporary file in a folder of your choice:
try {
// folder to create temporray file
File folder = new File("dir");
// create temporary file
File file = File.createTempFile("file-", ".tmp", folder);
// print path
System.out.println(file.getAbsolutePath());
} catch (IOException ex) {
ex.printStackTrace();
}
Further Reading
You may be interested in other Java I/O articles:
- Reading and Writing Files in Java
- How to Read and Write Text Files in Java
- How to Read and Write Binary Files in Java
- Reading and Writing Files using Java NIO API
- How to read a file line by line in Java
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.