Last Updated:

Creating Temporary Files in Java

Today we will learn how to create temporary files in Java. As usual, first a little theory and general concepts, and then in practice we will consolidate everything.

Create temporary files in Java. Theory

Sometimes we need to create a temporary file that will only be used in our application. There are two ways in which we can create a temporary file. All solutions are present in the standard class:java.io.File

Method createTempFile(String prefix, String suffix, File directory):

  • This method creates a file with a specific suffix and prefix in the specified folder.
  • The argument must already exist and must be a directory, otherwise an exception will be thrown.File directory
  • The file name is created by using the formula . This is done for the security of the application, since no one will know the file name and your program alone will run as a temporary file.prefix + random_long_no + suffix
  • prefix must be at least three characters long.
  • If is , then the default is ""."suffixnull.tmp
  • If passed to the parameter, then a temporary file is created in the standard directory for the temporary file of the operating system.directorynull

Method createTempFile(String prefix, String suffix):

This is the easiest way to create a temporary file in the standard folder for the temporary file operating system.

Create temporary files in Java. Practice

Here's a small example that shows how to create a temporary file.

It should be noted that we can work with temporary files as well as with regular files. temporary files must be deleted after the program has finished running.