Java — How to delete a file or directory | Code Factory

Code Factory
2 min readJul 21, 2020

--

Donate : Link

WordPress Blog : Link

You’ll learn how to delete a file or directory in Java. The article demonstrates two ways of deleting a File -

Delete File using Java NIO’s Files.delete() (Recommended) — JDK 7+

package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class DeleteFileExample {
public static void main(String... args) {
// File or Directory to be deleted
Path path = Paths.get("folder/folder1/test.txt");
try {
// Delete file or directory
Files.delete(path);
System.out.println("File or directory deleted successfully");
} catch (NoSuchFileException ex) {
System.out.printf("No such file or directory: %s\n", path);
} catch (DirectoryNotEmptyException ex) {
System.out.printf("Directory %s is not empty\n", path);
} catch (IOException ex) {
System.out.println(ex);
}
}
}

Output :

File or directory deleted successfully

There is another method deleteIfExists(Path) that deletes the file, but it doesn’t throw an exception if the file doesn’t exist.

// Delete file or directory if it exists
boolean isDeleted = Files.deleteIfExists(path);
if(isDeleted) {
System.out.println("File deleted successfully");
} else {
System.out.println("File doesn't exist");
}

Delete File in Java using File.delete method — JDK 6

You can use the delete() method of java.io.File class to delete a file or directory. Here is an example:

package com.example.java.programming.file;import java.io.File;/**
* @author code.factory
*
*/
public class DeleteFileExample {
public static void main(String... args) {
// File to be deleted
File file = new File("folder/folder1/test.txt");
// Delete file
boolean isDeleted = file.delete();
if(isDeleted) {
System.out.println("File deleted successfully");
} else {
System.out.println("File doesn't exist");
}
}
}

Output :

File deleted successfully

--

--