Temp Directory For Scratch Files
Create a per-run scratch directory with Files.createTempDirectory, write working files inside it, and clean everything up recursively on shutdown.
Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.stream.Stream;
public class ScratchWorkspace {
public static void main(String[] args) throws IOException {
// 前缀 + 随机后缀:并发运行互不冲突,目录落在系统临时区
Path scratch = Files.createTempDirectory("batch-");
System.out.println("scratch: " + scratch);
Path work = scratch.resolve("input.txt");
Files.writeString(work, "row-1\nrow-2\n");
// 直接在临时目录里再建子目录与文件,工作现场集中一处
Path nested = Files.createDirectories(scratch.resolve("out"));
Files.writeString(nested.resolve("result.txt"), "done");
System.out.println("written: " + Files.readAllLines(work).size() + " rows");
// 清理:按名字倒序逐个删除,子内容先于父目录消失
try (Stream<Path> paths = Files.walk(scratch)) {
paths.sorted(Comparator.reverseOrder()).forEach(p -> {
try {
Files.deleteIfExists(p);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
System.out.println("removed: " + Files.notExists(scratch));
}
}How the snippet works
All of the logic lives in the class ScratchWorkspace.
try-with-resources closes each declared resource automatically on every exit path. The failure path is explicit — RuntimeException wraps the IOException from Files.deleteIfExists while the cleanup walk is deleting the tree.
Caveats
- Nothing to install: the snippet stays inside the standard library.
Applying it
Labels prefix the printed lines — scratch:, written:, removed: — when the file runs.
Statements that matter
throw new RuntimeException(e);
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How does the code behave when input is bad?
- Validation comes first — `RuntimeException` marks the failure, before any partial work happens.
- What does Temp Directory For Scratch Files print when run?
- Execute the whole file; each printed line is prefixed with a label like `scratch:`, `written:`, `removed:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.