How to Delete File in Java


In this example, we will learn the methods to delete a file in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class FileOperator9Example { 
	public static void main(String[] args )
    {	
		try
        {
        	 File path = new File("example.txt");
        	 if (!path.exists()) 
        	 {
        		 path.createNewFile();
        	 }
        	 
        	 if(path.delete())
        	 {
     			System.out.println("Deleted successfully!");
     		 }
        	 else
        	 {
     			System.out.println("Delete failed.");
     		 }
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Output:

Deleted successfully!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments