Java Code to Delete a File


Delete a File in Java

Though a very simple process, it is very important. It is one of the most basic aspects of File Handling. So this Java Blog has decided to pick this topic in this tutorial.

The Java Code discussed today, starts by taking the path for the file, and checks for its existence. If the file exists, then the delete() command is fired on it. After deletion of the file, the presence of the file is checked. This step is to ensure that the deletion activity of the file is properly achieved or not.

The Java code is provided below:-

/////////////////////////////////

package developer;

import java.io.File;

public class DeleteFile {

public static void main(String[] args) {

File fileTest = new File("D:\\JavaCodeFile\\WriteTest.txt");

//Check for the existence of the file before deletion of it
System.out.println("Is the file present in the current location before deletion? ");
System.out.println(fileTest.exists());

if(fileTest.exists())
{
//Delete the file
fileTest.delete();
}

//Check for the existence of the file after deletion of it
System.out.println("Is the file present in the current location after deletion? ");
System.out.println(fileTest.exists());
}
}

/////////////////////////////////

This Java Code when executed on my JVM, resulted in the following output.

/////////////////////////////////

Is the file present in the current location before deletion? 
true
Is the file present in the current location after deletion? 
false

/////////////////////////////////