Creating a Temporary File in Java

Creating a temporary file can be required in many scenarios, but mostly during unit tests where we don’t want to store the output of the intermediate operations. As soon as the test is finished, we do not need these temp files and we can delete them.

If the target directory argument is not specified, the file is created in the default temp directory specified by the system property

  1. Windows – %USER%\AppData\Local\Temp
  2. Linux – /tmp

While unit testing using Junit, we can use TemporaryFolder as well. The TemporaryFolder rule allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails).

1. Using File.createTempFile()

The createTempFile() method is an overloaded method. Both methods will create the file only if there is no file with the same name and location that exist before the method is called.

If we want the file to be deleted automatically, use the deleteOnExit() method.

File createTempFile(String prefix, String suffix) throws IOException
File createTempFile(String prefix, String suffix, File directory) throws IOException
File temp;
   temp = File.createTempFile("testData", ".txt");
   System.out.println("Temp file created : " + temp.getAbsolutePath());
catch (IOException e)

Program Output:

Temp file created : C:\Users\Admin\AppData\Local\Temp\testData3492283537103788196.txt

2. Using Files.createTempFile()

This createTempFile() is also an overloaded method. Both methods create a new empty temporary file in the specified directory using the given prefix and suffix strings to generate its name.

If we want the file to be deleted automatically, open the file with DELETE_ON_CLOSE option so that the file is deleted when the appropriate close() method is invoked. Alternatively, a shutdown-hook, or the File.deleteOnExit() mechanism may be used to delete the file automatically.

Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs)
Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs)

In the given example, the created temporary file will be deleted when the program exits.

   final Path path = Files.createTempFile("myTempFile", ".txt");
   System.out.println("Temp file : " + path);
   //Delete file on exit
} catch (IOException e)

Happy Learning !!

Sourceocde on Github

Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.