java.io.File class can be used to create temp file in java. Sometimes we need to create temporary files to be used by our application.

Java Temp File

There are two methods in File class that we can use to create temp file in java.

  1. createTempFile(String prefix, String suffix, File directory): This method creates a temp file with given suffix and prefix in the directory argument.The directory should already be existing and should be a directory, else it throws exception.The file name is created with random long number, so the file name becomes prefix+random_long_no+suffix.This is done to make the application safe as it will be impossible to guess the file name and since application has instance of temp file, we can use it. The prefix String should be minimum three characters long. If suffix is null, “.tmp” suffix is used.

    If directory is null, then temp file is created in operating system temp directory.

  2. createTempFile(String prefix, String suffix): It’s easy way to create temp file in operating system temp directory.

Java Temp File Example

Here is a small java temp file example program.

Output of the above java temp file program is:

java-temp-file

That’s all about creating temp file in java.

By admin

Leave a Reply

%d bloggers like this: