If your application needs to create temporary files for some application logic or unit testing, then you would like to make sure that these temporary files are deleted when they are not needed. Let’s learn how to delete temporary files in java.
Deleting temporary file using File.deleteOnExit() or File.delete()
To delete a file when apllication exists or completes, you can use :
File temp = File.createTempFile("myTempFile", ".txt"); temp.deleteOnExit();
To delete the file, immediately without waiting for application exit, you can directly use delete()
method.
File temp = File.createTempFile("myTempFile", ".txt"); temp.delete();
Example Code for deleting temporary file
import java.io.File; import java.io.IOException; public class TemporaryFileExample { public static void main(String[] args) { File temp; try { temp = File.createTempFile("myTempFile", ".txt"); System.out.println("Temp file created : " + temp.getAbsolutePath()); //temp.delete(); //For deleting immediately temp.deleteOnExit(); //Delete on runtime exit System.out.println("Temp file exists : " + temp.exists()); } catch (IOException e) { e.printStackTrace(); } } }
Writing data to temporary file using NIO
If you want to use java NIO library, then you can use Files.delete()
or Files.deleteIfExists()
methods.
public class TemporaryFileExample { public static void main(String[] args) { try { final Path path = Files.createTempFile("myTempFile", ".txt"); System.out.println("Temp file : " + path); //Delete file on exit Files.deleteIfExists(path); //Delete file immediately Files.delete(path); } catch (IOException e) { e.printStackTrace(); } } }
Happy Learning !!
Files.deleteIfExists() is not equivalent to File.deleteOnExit() does. It simply deletes the file immediately.
If file is under /tmp, it would automatically be deleted by the OS right?
Not necessarily. As much I know, nothing happens automatically.. 🙂