Thursday, September 10, 2009

Java Code to Delete a File

Hello and welcome back to Java Code Online. The topic for today's discussion is to 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

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

Simple isn't it. yes the process of deletion of a file is very simple, and now you know it too. Keep checking Java Code Online for more Java articles.

Related articles that might be of interest:-
Java Code to Read a File
Java Code to Write to a File
Java Code to Create to a File
Java Code for File Extension
Java Code for Removing File Extension

1 comment:

  1. This article was really helpful. The Java Codes provided on your blog are great. It has been very handy for me to get codes from here for my own work. Great Job. Do post more articles on Java File Handling. I am looking forward for it.

    ReplyDelete

Note: Only a member of this blog may post a comment.