Skip to main content

How to Delete Files using Java


In this tutorial, we will create a program that can delete files using Java. We are done with creating files, appending, and reading data inside of a file. So, now let's start this tutorial! 1. Open Notepad. Encode any data in there and save it to the same folder with your java program and named it as data.txt. 2. Open JCreator or NetBeans and make a java program with a file name of 3. Import package. Hence we will use an input/output in creating files. Import also javax.swing package because we will use the JOptionPane.showMessageDialog here.
  1. import*;
  2. import javax.swing.*;
4. In your main, initialize the data.txt that you have created a while ago for this file. This data.txt file is the file that we will going to delete.
  1. File file = new File("data.txt");
5. Now, we will create an if-else statement that checks if the file is exists before deletion.
  1. if (file.exists())
  2. {
  3. JOptionPane.showMessageDialog(null, "Deleting file " + file.getAbsolutePath());
  5. // Use the delete method to delete the given file.
  6. file.delete();
  8. JOptionPane.showMessageDialog(null, "File Successfully Deleted!");
  9. }
If the file doesn't exist:
  1. else
  2. {
  3. JOptionPane.showMessageDialog(null, file.getAbsolutePath() + " doesn't exists.");
  5. }
Output: output Here's the full code of this tutorial:
  1. import*;
  2. import javax.swing.*;
  4. public class deleteFiles
  5. {
  6. public static void main(String[] args)
  7. {
  8. // When want to delete a file named data.txt
  9. File file = new File("data.txt");
  11. // Checks if the file is exists before deletion.
  12. if (file.exists())
  13. {
  14. JOptionPane.showMessageDialog(null, "Deleting file " + file.getAbsolutePath());
  16. // Use the delete method to delete the given file.
  17. file.delete();
  19. JOptionPane.showMessageDialog(null, "File Successfully Deleted!");
  20. } else
  21. {
  22. JOptionPane.showMessageDialog(null, file.getAbsolutePath() + " doesn't exists.");
  24. }
  25. }
  26. }
Hope this program helps :) Best Regards, Engr. Lyndon R. Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: Visit and like my page on Facebook at:

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.


1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment