In this simple and quick article, you’ll learn how to delete a file or directory in Java. The article demonstrates two ways of deleting a File -
- Delete file using Files.delete(Path) method of Java NIO
- Delete file using the delete() method of
java.io.File
class
Delete File using Java NIO’s Files.delete() (Recommended) - JDK 7+
import java.io.IOException;
import java.nio.file.*;
public class DeleteFileExample {
public static void main(String[] args) throws IOException {
// File or Directory to be deleted
Path path = Paths.get("./demo.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);
}
}
}
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:
import java.io.File;
public class DeleteFileExample1 {
public static void main(String[] args) {
// File to be deleted
File file = new File("foo.txt");
// Delete file
boolean isDeleted = file.delete();
if(isDeleted) {
System.out.println("File deleted successfully");
} else {
System.out.println("File doesn't exist");
}
}
}
Note that, you can delete an empty directory using the same approach as discussed in the above examples. But if you want to delete a non-empty directory recursively then check out this article -
How to delete a directory recursively with all its subdirectories and files in Java