How to delete file in java ?

In this section we will learn how to write a program to delete a file in java. You can delete the file or folder, java File class provide two methods.

How to delete file in java ?

In this section we will learn how to write a program to delete a file in java. You can delete the file or folder, java File class provide two methods.

How to delete file in java ?

How to delete file in java ?

In this section we will learn how to write a program to delete a file in java. You can delete the file or folder, java File class provide two methods:

delete(path) : This method delete the file or throw an exception if file not deleted. delete() is a static method, to delete a directory then directory should be empty.

deleteIfExists(path) : This method also delete file but if file does not exist then it will not throw an exception.

Now, here is the code to delete a file in java.

import java.io.File;
 
public class DeleteFile
{
    public static void main(String[] args)
    {	
    	try{
 
    		File files = new File("C://Documents and Settings//satya//Desktop//shashi//coreJavaExample//DeleteFile//text.txt");
 
    		if(files.delete())
                                             {
    			System.out.println("File  is deleted!");
    		             }   else
                                                      {
    			System.out.println("Deletion  is failed.");
    		                    }
 
    	}catch(Exception e){
 
    		e.printStackTrace();
 
    	}
 
    }
}

Output : After compiling and executing the above program

Download SourceCode