Java IOjava-io-examples

How to Delete a file

Posted On
Posted By admin

In this blog post, I will be demonstrating how you can delete a file in Java. Consider the following code snippet:


package learnjava.io;

import java.io.File;

public class DeleteFile {

public static void main(String[] args) {
String fileName = "D:/Test.txt";
File file = new File(fileName);
if (file.exists()) {
if (file.delete()) {
System.out.println("Deleted file successfully");
} else
System.out.println("Error in deleting file");
} else
System.out.println("File is missing, so could not be deleted");
}

}

 

There is a File.delete method available to delete a file. It returns true, if the delete was successful, otherwise returns a false. So if you run the above code snippet, the following output will be printed (Assuming there is a file called test.txt on D Drive):

 

Deleted file successfully
If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment