dcsimg

How do I create a temporary file?

John Zukowski

To create a temporary file, use the createTempFile() method of the File class. This allows you to set the file prefix, suffix, and directory. If no directory is specified, then the java.io.tmpdir System property is used. To ensure the file is deleted when the program ends (assuming normal termination), be sure to call the deleteOnExit() method of the File object created by createTempFile().

File temp = File.createTempFile("jguru", ".tmp");
temp.deleteOnExit();
// use temp like any other File