Java Reference
In-Depth Information
// 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
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
public static
void writeDataInTemp ( String tempnam ) {
// This version is dummy. Use your imagination.
static void
}
}
Notice that the createTempFile() method is like createNewFile() (see Creating a File ) in
that it does create the file. Also be aware that, should the Java Virtual Machine terminate ab-
normally, the deletion probably does not occur. There is no way to undo the setting of de-
leteOnExit() short of something drastic like powering off the computer before the program
exits.
And, deleteOnExit() is probably not what you want to use in a long-running application,
like most server-side apps. In these situations, the server could be running for weeks,
months, or even years, and in the meantime all the temp files would accumulate, and the
JVM would accumulate a large list of deferred work that it needs to perform upon shutdown.
You'd probably run out of disk space or server memory or some other resource. For most
long-running apps of this kind, it's better to use the explicit delete() operation, or else use a
scheduler service to periodically trigger removal of old temporary files.
Search WWH ::




Custom Search