In this tutorial you will how to delete files in Java?
Delete a File using File Class Object
Delete a File using File Class Object
In this section, you will learn how to delete a file. For deleting a file, first we, creates a new File instance by converting the given pathname string into an abstract pathname using object of the File class. Secondly, we use the delete() function to delete the file.
Given below example will give you a clear idea :
Example :
import java.io.*; public class DeleteFile { public static void main(String[] args) { boolean success = (new File("file.txt")).delete(); if (success) { System.out.println("The file has been successfully deleted"); } else { System.out.println("File Doesn't Exist"); } } }
Output :
If file deletion operation is successful, it will show :
The file has been successfully deleted |
If file doesn't exist or any occurred in deleting file, it will show:
Some error occurred |