Create temporary file with specified extension suffix in Java


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

A program that demonstrates this is given as follows −

Example

 Live Demo

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

The output of the above program is as follows −

Output

C:\Users\amit_\AppData\Local\Temp\temp3879834079458072093.java

Now let us understand the above program.

A temporary file with the specified extension suffix 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 file = File.createTempFile("temp", ".java");
System.out.println(file.getAbsolutePath());
file.deleteOnExit();

Updated on: 30-Jul-2019

788 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements