Java File temporary and renamed files
Create scratch files, rename a completed draft, or arrange deletion when the JVM exits normally.
A simple example
File temporary and renamed files
- Start with A file named a.txt
- Do this Rename it to b.txt
- Result b.txt holds the original contents
Syntax
public boolean renameTo(File dest)
JDK 21 declarations (5)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPublish a completed draft under its final name
A ticket desk writes a draft to a fresh temporary file beside the intended receipt. Once ready, it tries to rename the file in the same directory and removes this practice receipt when the exercise finishes.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
File draft = File.createTempFile("ticket-", ".tmp", desk.toFile());
File receipt = new File(desk.toFile(), "ticket.txt");
if (!draft.renameTo(receipt)) throw new IOException("Cannot rename draft");
System.out.println(receipt.getName());
System.out.println(receipt.delete());
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
ticket.txt true
The target is new and on the same disk. A failed rename is handled before the program uses the destination.
Register a disposable preview for shutdown
A small desktop tool generates a preview that should survive until the session ends. Register the scratch file for a normal shutdown and check that scheduling deletion leaves the current preview available.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
File preview = File.createTempFile("preview-", ".txt", desk.toFile());
preview.deleteOnExit();
System.out.println(preview.exists());
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true
Registration does not remove the file immediately. The surrounding exercise also performs immediate cleanup when it finishes.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Rename the draft to its final name. What text can the next shift read under that name?
What to watch for
renameTo depends on the platform and returns a boolean. deleteOnExit runs on normal JVM termination and is a poor fit for frequent cleanup in long-lived services.