Create temporary file in specified directory in Java


A temporary file in the specified directory can be created using the method java.io.File.createTempFile(). This method requires three parameters i.e. the prefix to define the file name, the suffix to define the file extension and the directory in which the temporary file is to be created. It also returns the abstract path name for the temporary file created.

A program that demonstrates this is given as follows −

Example

import java.io.File;
public class Demo {  
   public static void main(String[] args) throws Exception {
      File directory = new File("C:/JavaProgram");
      File file = File.createTempFile("temp", ".java", directory);
      System.out.println(file.getAbsolutePath());
      file.deleteOnExit();
   }
}

The output of the above program is as follows −

Output

C:\JavaProgram\temp1333744144499445058.java

Now let us understand the above program.

A temporary file in the specified directory is created using the method java.io.File.createTempFile(). Then the file path is displayed. Also, the method java.io.File.deleteOnExit() is used to delete the temporary file after the program ends. A code snippet that demonstrates this is given as follows −

File directory = new File("C:/JavaProgram");
File file = File.createTempFile("temp", ".java", directory);
System.out.println(file.getAbsolutePath());
file.deleteOnExit();

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements