Java - Delete file or directory example

Posted on November 2, 2016


In this example, we will show you how to use the delete() method of the File class to delete a file or directory. The delete() method return true if the file or directory deleted successfully; otherwise false.

Here is an example of File.delete().

DeleteFileDirectoryExample.java

package com.boraji.tutorial.io;

import java.io.File;

/**
 * @author imssbora
 * DeleteFileDirectoryExample.java
 * Nov 2, 2016
 */
public class DeleteFileDirectoryExample {
	public static void main(String[] args) {
		
		/*Delete single file*/
		System.out.println("-------------Deleting single file--------------");
		File file=new File("test.txt");
		if(file.exists()){
			if(file.delete()){
				System.out.println("File deleted successfully");
			}else{
				System.out.println("Fail to delete file");
			}
		}
		
		System.out.println("\n-------------Deleting multiple files--------------");
		/*Delete all files in directory*/
		File folder=new File("folder");
		if(folder.exists() && folder.isDirectory()){

			for (File f : folder.listFiles()) {
				if(f.delete()){
					System.out.println("'"+f.getName()+"' deleted successfully");
				}else{
					System.out.println("Fail to delete '"+f.getName()+"'");
				}
			}
		}
		
		/*Delete folder*/
		System.out.println("\n-------------Deleting folder--------------");
		if(folder.exists() && folder.isDirectory()){
			if(folder.delete()){
				System.out.println("Folder deleted successfully");
			}else{
				System.out.println("Fail to delete folder");
			}
		}
	}
}

Sample output

-------------Deleting single file--------------
File deleted successfully

-------------Deleting multiple files--------------
'test.txt' deleted successfully
'test2.txt' deleted successfully
'test3.txt' deleted successfully
'test4.txt' deleted successfully
'test5.txt' deleted successfully
'test6.txt' deleted successfully
'test7.txt' deleted successfully

-------------Deleting folder--------------
Folder deleted successfully