Learn How to Delete Files in Java
How to Delete File in Java?
Deleting a file in Java is a relatively straight-forward process. To delete a file, or directory, you will need to make use of the java.io.File
class. This class provides methods that can be used to delete files and directories.
Step 1: Import Packages
You will need to import the following packages in your program to use the java.io.File
class:
import java.io.File;
import java.io.IOException;
Step 2: Create an Object of the File Class
To delete a file, you will first need to create an object of the java.io.File
class using the file path as the parameter. The code to do this would look like this:
File myFile = new File("C:/myfile.txt");
Step 3: Call the delete Method
Once you have created your file object, you can then call the delete()
method on the object. This method will delete the file from your hard drive. It is important to remember that the file does not need to exist for this method to be called. The code to do this would look like this:
myFile.delete();
Step 4: Catch IOExceptions
The delete()
method throws an IOException
, so you will need to ensure that you catch it. The code to do this would look like this:
try {
myFile.delete();
} catch(IOException e) {
e.printStackTrace();
}
And that’s it! You have successfully deleted a file from your computer using the java.io.File
class.