Thursday, May 17, 2007

Delete a File in Java

This short tutorial shows how to delete a file in Java. First, you will need to create a File object for the file. Once you have created a File object, you can call the delete method. This method will return true if the file was deleted.

       File file = new File("c:/temp/test.txt");
boolean success = file.delete();

if (success)
{
//File was deleted
System.out.println("File was deleted.");
}
else
{
//File was not deleted
System.out.println("File was not deleted.");
}

If it fails in deleting the file (maybe because of a file lock), you can request the JVM to delete the file when it exits using the deleteOnExit() method on the File object.

0 comments: