Deleting Directory in Java

Deleting Directory in Java

It is possible to delete an empty directory. In this post, we will learn Deleting Directory in Java with contents. Deleting entire directory or directories with content is not simple in Java. Java 7  came up with easy and elegant solutions to address such requirements.

We will be covering following options

  1. Delete directories in Java using Java 7  FileVisitor.
  2. Apache Commons FileUtils.

 

1. Delete Directory Using Java

If we run following Java program assuming that root location is not empty (there are more directories inside tutorials directory)

 


public class DeleteDirectory {

  public static void main(String[] args) throws IOException {
        Path path = Paths.get("/Users/personal/tutorials");
        Files.delete(path);
    }
}

We will get following exception


Exception in thread "main" java.nio.file.DirectoryNotEmptyException: /Users/personal/tutorials
	at sun.nio.fs.UnixFileSystemProvider.implDelete(UnixFileSystemProvider.java:242)
	at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
	at java.nio.file.Files.delete(Files.java:1126)
	at com.umeshawasthi.tutorials.corejava.io.directory.delete.DeleteDirectory.main(DeleteDirectory.java:15)

 

1.1 Delete Directory Using Java 7

With Java 7+ We can use convenient Files class

public class DeleteDirectory {

    public static void main(String[] args) throws IOException {
        Path rootDirectory = Paths.get("/Users/personal/tutorials/Write");

        Files.walkFileTree(rootDirectory, new SimpleFileVisitor() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

 

1.2 Delete Directory Using Java NIO and Stream API

Java NIO and Stream API provides elegant options of deleting the directory in Java recursively.


public class DeleteDirectoryByStream {

    public static void main(String[] args) throws IOException {

        Path rootDirectory = Paths.get("/Users/personal/tutorials/stream");
        Files.walk(rootDirectory)
                .sorted(Comparator.reverseOrder())
                .map(Path::toFile)
                .forEach(File::delete);
     }
}

 

Here are few details for the above code

  1. Files.walk will return all files/directories under rootDirectory.
  2. We are using Comparator.reverseOrder() to ensure the main directory will be picked in the last.
  3. map Returns a File object representing this path.
  4. forEach will call delete method for each File object.

 

Above code block will not delete symlinks.To follow and delete symlinks use FileVisitOption.FOLLOW_LINKS as an additional parameter. Files.walk(rootDirectory, FileVisitOption.FOLLOW_LINKS)

 

1.1 Delete Directory Using Apache Commons

 

If your project is using Apache Commons, FileUtils provides an easier one line solution for Deleting Directory in Java.

 

public class DeleteDirectoryByApache {

    public static void main(String[] args) throws IOException {

        FileUtils.deleteDirectory(new File("/Users/personal/tutorials/apachecommons"));
    }
}

The code will not throw any exception in case path/ location is not correct.

Include Apache commons in your project if you want to use Apache Commons.

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.5</version>
</dependency>

 

If you want to create directory using Java NIO, read How to create directory in Java

 

All the code of this article is available Over on Github. This is a Maven-based project.

References

  1. FileVisitResult
  2. Files#walk
  3. FileUtils#deleteDirectory
  4. FileVisitOption#FOLLOW_LINKS

Comments are closed.