Java File Delete and DeleteOnExit - Java @ Desk

Saturday, December 7, 2013

Java File Delete and DeleteOnExit

Java File Delete and DeleteOnExit
To delete a file in java, following package is getting used
1) import - To handle file operations
2) import - To handle any exceptions occur during the directory operation

While creating a directory, following things need to be checked:
1) Check if the file exists using the exists() method. Not mandarory
2) Make a call to delete() method

There are two ways to delete a file in java
1) delete() - Returns true if the file gets deleted successfully. It deletes the file immediately as soon as the delete() method gets called
2) deleteOnExit() - The method deletes the file or directory defined by the abstract path name when the virtual machine terminates. It's purpose is to delete the file when the JVM exits.
 package com.file;  
 public class FileDelete {  
      public static void main(String[] args) throws IOException, InterruptedException {  
           File file = new File("D:\\kumar\\Blogs\\File Operations\\newfile.txt");  

Check delete() operation by commenting last two lines.
In order to test deleteOnExit() implementation, perform following:
1) Create the new file. Click here to do so
2) Put Thread.sleep(10000) or for suitable time as per your need.
3) Run the file, and check the folder. The file will not get delete as soon as the method got executes.
4) It will wait for the JVM to exit, so the file gets deleted once Thread.sleep() gets executed and JVM exits after this sleep.

No comments:

Post a Comment