How to create a temporary file in Java

The class File, in java, has a method to create a temp file when defining a prefix and a suffix.


File tmpFile = File.createTempFile("temp_", ".txt");

Here a an example creating a temporary File in the temporary directory defined in the JVM.

Create the following java file:


public class TmpFile {

    public static void main(String[] argv) {

	try {
	    File tmpFile = File.createTempFile("temp_", ".txt");

	    System.out.println("The tmp File is " + tmpFile.getAbsolutePath());
	} catch (IOException e) {
	    // TODO Auto-generated catch block


The output will be:

The tmp File is C:\Users\Olivier\AppData\Local\Temp\temp_738482536127269501.txt

Note: The File Object has a method to create the temp file, that uses a directory. In that case the file will be created in that directory. If no directory is passed, then the file is created in the directory.


class File Javadoc

Recent Comments