Create a Temporary File in Java

This short Java tutorial shows how to create a temporary file in Java.

When you call the static method createTempFile(), you can specify the prefix and suffix for the temporary file. The prefix must be atleast 3 characters. If the suffix is null, ".tmp" is used for suffix. You can also specify a third parameter for the directory. If you leave this parameter off, Java will place the temporary file in the correct location for your file system.

If the file cannot be created, the createTempFile() method will throw an IOException.

//Create temp file
File file = File.createTempFile("myprefix", ".tmp");

//Delete file when Java exits
catch (IOException ioe)
//File could not be created


Post a Comment