How to Delete Files in Java

May 29, 2020
Tutorials
delete

Today, we will be creating a program that can delete files using Java.

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 deleteFiles.java.

3. Import java.io package. Hence we will use an input/output in creating files. Import also javax.swing package because we will use the JOptionPane.showMessageDialog here.

import java.io.*;
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 be going to delete.

File file = new File("data.txt");

5. Now, we will create an if-else statement that checks if the file exists before deletion.

if (file.exists())
        {
        	JOptionPane.showMessageDialog(null, "Deleting file " + file.getAbsolutePath());
 
            // Use the delete method to delete the given file.
            file.delete();
 
            JOptionPane.showMessageDialog(null, "File Successfully Deleted!");
        }

If the file doesn’t exist:

else
        {
        	 JOptionPane.showMessageDialog(null, file.getAbsolutePath() + " doesn't exists.");
 
        }

Output:

output


Here’s the full code of this tutorial:

import java.io.*;
import javax.swing.*;
 
public class deleteFiles
{
    public static void main(String[] args)
    {
        // When want to delete a file named data.txt
        File file = new File("data.txt");
 
        // Checks if the file is exists before deletion.
        if (file.exists())
        {
        	JOptionPane.showMessageDialog(null, "Deleting file " + file.getAbsolutePath());
 
            // Use the delete method to delete the given file.
            file.delete();
 
            JOptionPane.showMessageDialog(null, "File Successfully Deleted!");
        } else
        {
        	 JOptionPane.showMessageDialog(null, file.getAbsolutePath() + " doesn't exists.");
 
        }
    }
}
Download Code
Facebook Comments

Leave a Reply

Your email address will not be published.