How to Delete a File In Java?

Category: Java   Tags: Java, Java File Handling, Java Path, Java NIO File System

While using Path you can delete a file, directory or a symbolic link. The directory must be empty in order to delete it. With symbolic links, the link is deleted and not the target of the link.

There are two ways of deleting files: delete(Path path) method deletes the file or throws an exception if the deletion fails. deleteIfExists(Path) method also deletes the file, but if the file does not exist, no exception is thrown.

Here is a simple Java program that shows how to delete the file:

JavaDeleteFileExample.java

                            package com.tutorial.java.files;

                            import java.io.IOException;
                            import java.nio.file.Files;
                            import java.nio.file.Path;
                            import java.nio.file.Paths;

                            public class JavaDeleteFileExample {

                                public static void main(String[] args) throws IOException {
                                    try {
                                        Path path = Paths.get("sample1.txt");
                                        Files.delete(path);
                                    } catch (IOException ex) {
                                        ex.printStackTrace();
                                    }

                                    try {
                                        Path path1 = Paths.get("sample2.txt");
                                        Files.deleteIfExists(path1);
                                    } catch (IOException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }