Temporary files play an important role in software development or app development. Here we are going to share a Java code for creating temp files.

Creating temp files using File.createTempFile(String1, String2):

We can create temp files on the runtime by using File.createTempFile(String1, String2). In this method, you will pass two strings. The first string will be the name of the temp file and the second string will be the extension.

Source code:

import java.io.File;
import java.io.IOException;

public class CreateTempFiles {
    
    public static void main(String[] args) {
        try {
 
            File tFile = File.createTempFile("Sample", ".tmp");
            System.out.println("Temporary file created successfully on default location!");
            System.out.println("Temporary file on default location: " + tFile.getAbsolutePath());
            System.out.println("Temporary file created successfully on specified location!");
            tFile = File.createTempFile("Sample2", ".tmp", new File("E:\\Java Programs"));
            System.out.println("Temporary file on specified location: " + tFile.getAbsolutePath());
 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Temporary file created successfully on default location!
Temporary file on default location: C:\Users\Lenovo\AppData\Local\Temp\Sample2971845896247109328.tmp
Temporary file created successfully on specified location!
Temporary file on specified location: E:\Java Programs\Sample25185422988610716803.tmp
BUILD SUCCESSFUL (total time: 6 seconds)

Deleting temp files:

Temp files are deleted automatically in Windows OS when the system restarts. But, what if we want to delete the temp files without restarting the system? Yes, you can delete the temp files by using the Java code given below:

Source code:

try
      {
        File tFile = File.createTempFile("Sample", ".temp");
          
         tFile.deleteOnExit(); 
         
          System.out.println("Deleted Successfully!!");
         
      } 
      catch (IOException e)
      {
         e.printStackTrace();
      }

Output:

run:
Deleted Successfully!!
BUILD SUCCESSFUL (total time: 3 seconds)

References: