Create a temporary file in Java

Java 8Object Oriented ProgrammingProgramming

A temporary file 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", null);
      System.out.println(file.getAbsolutePath());
      file.deleteOnExit();
   }
}

The output of the above program is as follows −

Output

C:\Users\amit_\AppData\Local\Temp\temp6072597842246154962.tmp

Now let us understand the above program.

A temporary file 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", null);
System.out.println(file.getAbsolutePath());
file.deleteOnExit();
raja
Published on 28-Feb-2019 11:25:00
Advertisements