Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Hubert Klein Ikkink (aka Mr.Haki) - Communications Officer
 Mr.Haki's JBuilder Jar #61
See Also: JBuilder Papers

Creating temporary files
Every once in a while we have to create a temporary file to store some information. We only want it to use in our application and it must have a unique name. Preferably we want to store the file in the system's temporary folder, so we don't have to do any housekeeping for storing the files.

Since JDK1.2 we can use the createTempFile() method in the File class. This method is a static method and returns a File object we can use to store information in. We don't have to worry about uniqueness of the name, because the Java VM will take care of that. And the file can be created in the system's temporary folder automatically.

The createTempFile() method has three parameters:

Let's take a look at a small example, in which the createTempFile() method is used.

    File tempFile = null;
    try {
      tempFile = File.createTempFile("www.drbob42.com", ".tmp");
      System.out.print("Created temporary file with name ");
      System.out.println(tempFile.getAbsolutePath());
    } catch (IOException ex) {
      System.err.println("Cannot create temp file: " + ex.getMessage());
    } finally {
      if (tempFile != null) {
        tempFile.delete();
      }
    }
Running this code results in the following output:
  Created temporary file with name C:\TEMP\www.drbob42.com56873.tmp
We notice the file starts with the prefix www.drbob42.com followed by a number generated by the Java VM and the extension .tmp. The file is placed in the system's temporary folder, in this case C:\TEMP.


This webpage © 1997-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.