Master java skills

Deleting File in Java

Java File class provides delete() method to delete a file. This method returns a boolean value.

deleteFile.java

import java.io.File;

public class deleteFile {

	public static void main(String[] args) {
		File fileObj = new File("D:\\Java_Programs\\New Directory\\jst.txt");
		//deleting specified file
		if(fileObj.delete()){
		    System.out.println("File deleted successfully !");
		}
		else{
		    System.out.println("File has not deleted !");
		}
	}
}
Output :
File deleted successfully !

Delete Folder in Java

We can delete a folder by Java code. However the folder should be empty.

deleteFolder.java

import java.io.File;

public class deleteFolder {

	public static void main(String[] args) {
		File fileObj = new File("D:\\Java_Programs\\New Directory");
		//deleting 'New Directory' folder
		if(fileObj.delete()){
		    System.out.println(fileObj.getName() +" has been deleted successfully !");
		}
		else{
		    System.out.println("Fail to delete New Directory !");
		}
	}
}
Output :
New Directory has been deleted successfully !