// 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(); } } }
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.