Recipe 11.5 Creating a Transient File


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


Use a object's createTempFile( ) or deleteOnExit( ) method.


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. Both files are gone after the program runs:

import*; /**  * 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("");         // 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 Recipe 11.2) in that it does create the file. Also be aware that, should the Java Virtual Machine terminate abnormally, the deletion probably does 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.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: