O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a Transient File

Problem

You need to create a file with a unique temporary filename or arrange for a file to be deleted when your program is finished.

Solution

Use a java.io.File object’s createTempFile( ) or deleteOnExit( ) method.

Discussion

The File object has a createTempFile method and a deleteOnExit method. The former creates a file with a unique name -- in case several users run the same program at the same time on a server -- and the latter arranges for any file (no matter how it was created) to be deleted when the program exits. Here we arrange for a backup copy of a program to be deleted on exit, and we also create a temporary file and arrange for it to be removed on exit. Sure enough, both files are gone after the program runs.

import java.io.*; /** * Work with temporary files in Java. */ public class TempFiles { public static void main(String[] argv) throws IOException { // 1. Make an existing file temporary // Construct a File object for the backup created by editing // this source file. The file probably already exists. // My editor creates backups by putting ~ at the end of the name. File bkup = new File("Rename.java~"); // Arrange to have it deleted when the program ends. bkup.deleteOnExit( ); // 2. Create a new temporary file. // Make a file object for foo.tmp, in the default temp directory File tmp = File.createTempFile("foo", "tmp"); // Report on the filename that it made up for us. System.out.println("Your temp file is " + tmp.getCanonicalPath( )); // ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required