How to Delete a File in Java


In this example we will show the method to delete a file in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class DeleteFile {
    public static void main(String[] args )
    {
        try {
             File f = new File("example.txt");
             if(f.delete()) { // delete a file
     			System.out.println("Deleted successfully!");
     		 } else {
     			System.out.println("Delete failed.");
     		 }
        } catch (IOException e) {
            System.out.println("Error.");
            e.printStackTrace();
        }
    }
}

Output:

Deleted successfully!

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments