You need to create a file with a unique temporary filename or arrange for a file to be deleted when your program is finished.
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( )); // Arrange for it to be deleted at exit. tmp.deleteOnExit( ); // Now do something with the temporary file, without having to // worry about deleting it later. writeDataInTemp(tmp.getCanonicalPath( )); } public static void writeDataInTemp(String tempnam) { // This version is dummy. Use your imagination. } }
Notice that the createTempFile
method is like
createNewFile
(see Section 10.3)
in that it does create the file. Also be aware that, should the Java
Virtual Machine terminate abnormally, the deletion will probably not
occur. Finally, there is no way to undo the setting of
deleteOnExit( )
short of something drastic like
powering off the computer before the program exits.
18.191.254.44