Library contents

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

  1. Start with A file named a.txt
  2. Do this Rename it to b.txt
  3. Result b.txt holds the original contents
After a successful rename in the same directory the old name disappears.

Syntax

Java 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.java

Publish 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.

First output lineticket.txt
Main.java
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);
            }
        }
    }
}
Output
ticket.txt
true

The target is new and on the same disk. A failed rename is handled before the program uses the destination.

Advertisements

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.

Resulttrue
Main.java
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);
            }
        }
    }
}
Output
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?

GivenFile contents “clay”
Worked resultclay

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.

Documentation for File temporary and renamed files