Java Files createTempFile() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, Files.createTempFile(prefix, suffix) creates a new, empty file with a unique name such as report-8304512938475.csv and returns its path. The name is the prefix, a random number, and the suffix, so it never collides with an existing file.

Without a folder argument it uses the system temp folder from the java.io.tmpdir property. The file is not removed automatically: delete it yourself, ideally in a finally block.

A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.createTempFile(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Two overloads: default temp folder, or a folder you choose:

Java
Path a = Files.createTempFile("report-", ".csv");          // in java.io.tmpdir
Path b = Files.createTempFile(dir, "upload-", ".part");    // inside dir
Path c = Files.createTempFile(null, null);                 // e.g. 4711.tmp
CallWhat it does
createTempFile(prefix, suffix)New file in the default temp folder.
createTempFile(dir, prefix, suffix)New file inside dir.
createTempFile(p, null)A null suffix means .tmp.
file.toFile().deleteOnExit()Asks the JVM to delete it at normal exit (use sparingly).

Since Java 7. On Linux and macOS the new file is created with owner-only permissions (rw-------), which is safer than java.io.File.createTempFile on older Java versions. You can pass other attributes as the last argument.

Library declarations
Java
public static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException
public static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) throws IOException

Parameters

ParameterDescription
dir(Second overload) Folder to create the file in; it must exist.
prefixStart of the name, or null for none.
suffixEnd of the name, such as ".csv"; null means ".tmp".
attrsOptional attributes, for example POSIX permissions.

Return Value

Return ValueDescription
PathThe new empty file. Its exact name is random, so print only parts you control.

Compare with Similar Methods

Temporary and regular creation:

MethodHow it differs
createTempDirectory()Same idea for a whole scratch folder.
createFile()You choose the exact name, and it fails if taken.
deleteIfExists()The usual cleanup call in a finally block.

Java Examples

Example 1 — A Temp File with a Recognisable Name

Create a temp file inside a demo folder and check its name pattern instead of printing the random part.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CreateTempFileNamed {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path tmp = Files.createTempFile(dir, "report-", ".csv");
        String name = tmp.getFileName().toString();
        System.out.println("Starts with report-: " + name.startsWith("report-"));
        System.out.println("Ends with .csv: " + name.endsWith(".csv"));
        System.out.println("Inside the demo folder: " + tmp.getParent().equals(dir));
        System.out.println("Size: " + Files.size(tmp));
        Files.delete(tmp);
        Files.delete(dir);
    }
}

How It Works

  1. Folder overload. Passing dir first puts the file inside the demo folder instead of the shared system temp folder.
  2. Random middle. The name is report-, then a random number, then .csv, so the program checks the start and the end rather than printing a value that changes every run.
  3. Empty on creation. Like createFile, the new file has size 0 until you write to it.

Example 2 — Default Folder and the .tmp Suffix

With null for both arguments the file lands in java.io.tmpdir and ends with .tmp.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateTempFileDefaults {
    public static void main(String[] args) throws IOException {
        Path tmp = Files.createTempFile(null, null);
        try {
            System.out.println("Ends with .tmp: " + tmp.getFileName().toString().endsWith(".tmp"));
            Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir"));
            System.out.println("In java.io.tmpdir: " + Files.isSameFile(tmp.getParent(), tmpDir));
            Path second = Files.createTempFile(null, null);
            System.out.println("Second file has another name: " + !second.equals(tmp));
            Files.delete(second);
        } finally {
            Files.delete(tmp);
        }
    }
}

How It Works

  1. Defaults kick in. No prefix and no suffix give a name made of digits plus .tmp.
  2. Where it went. isSameFile compares the file's folder with the java.io.tmpdir folder, which also works on macOS where the temp path goes through a symbolic link.
  3. Never the same twice. A second call picks a different random number, so the two paths differ.
  4. finally guarantees cleanup. The first file is deleted even if one of the checks had thrown.

Example 3 — Write, Read, and Delete a Scratch File

Use a temp file as short-lived storage and remove it with deleteIfExists in finally.

Java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class CreateTempFileScratch {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path part = Files.createTempFile(dir, "upload-", ".part");
        try {
            Files.write(part, "chunk-1;chunk-2".getBytes(StandardCharsets.UTF_8));
            System.out.println("Bytes written: " + Files.size(part));
            String text = new String(Files.readAllBytes(part), StandardCharsets.UTF_8);
            System.out.println("Read back: " + text);
        } finally {
            System.out.println("Deleted: " + Files.deleteIfExists(part));
            Files.delete(dir);
        }
        System.out.println("Still exists: " + Files.exists(part));
    }
}

How It Works

  1. A partial upload. The .part file holds data that only matters while the program runs, the classic use for a temp file.
  2. Plain ASCII, easy size. "chunk-1;chunk-2" is 15 characters, and each ASCII character is one UTF-8 byte, so the size is 15.
  3. Report the cleanup. deleteIfExists returns true because the file was there; it would return false rather than throw if something had already removed it.

Frequently Asked Questions

In the folder named by the java.io.tmpdir system property, unless you use the overload that takes a directory as its first argument.
No. Delete them yourself, typically with Files.deleteIfExists in a finally block. path.toFile().deleteOnExit() deletes at normal JVM exit, but every registration uses memory until then.
The suffix ".tmp" is used. A null prefix simply means the name starts with the random number.
No. The method retries with a new random name until it can create a file that did not exist, and creation is atomic.
On Linux and macOS, owner read and write only (rw-------). On Windows the file inherits the permissions of the temp folder.

Next: Files.delete()

Delete a file or an empty folder; throws if it is missing or the folder is not empty.

delete() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful