// Create temp file import java.io.File; import java.io.IOException; public class tempFile { public static void main(String args[]) throws IOException { // name of the file String prefix = "TempFile"; // extention of the file String suffix = ".txt"; // Creating a File object for directory File directoryPath = new File( "/home/krishna/Desktop/java/junior/"); // Creating a temp file File.createTempFile(prefix, suffix, directoryPath); System.out.println( "Temp file created at the specified path"); } }
Output:
Temporary file has been created in the specified path
There are two ways you can delete an existing temporary file.
A. Delete when JVM exits:
// Delete File when JVM Exists import java.io.File; import java.io.IOException; public class tempFile { public static void main(String[] args) { File temp; try { // name of the file and extention temp = File.createTempFile("TempFile", ".txt"); // Delete when JVM exits temp.deleteOnExit(); } // If not found any temporary file catch (IOException e) { e.printStackTrace(); } } }
B. Delete the file immediately:
We can delete a temporary file with the use delete() method.
// Delete file using delete() method import java.io.File; import java.io.IOException; public class tempFile { public static void main(String[] args) { File temp; try { temp = File.createTempFile("myTempFile", ".txt"); // Perform other operations // Delete the file immediately temp.delete(); } // If not found the temperory file catch (IOException e) { e.printStackTrace(); } } }