This section focuses on java nio delete directory tutorial which demonstrates the usage of the new api that deals with I/O. Using the java nio in deleting the directory is simple, we just have to access the walkFileTree method of Files class of java.nio.file package. And then by overriding the visitFile method, we will delete the file contents of the current working directory. After we have deleted the file contents of the current directory, we will delete the parent folder by overriding the method postVisitDirectory. We are doing the deletion of files as we are traversing the file contents of the path directory.
JAVA NIO Delete Directory Sample Sourcecode
package com.javatutorialhq.tutorial; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; // Java NIO Delete Directory public class FolderDeleteNIO { public static void main(String[] args) throws IOException { //declaring the path to delete Path path = Paths.get("E:/tmp/java/tutorial/nio/file/delete"); System.out.println("Deleting recursivey : "+path); //browsing the file directory and delete recursively using java nio Files.walkFileTree(path, new FileVisitor() { @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { System.out.println("deleting directory :"+ dir); Files.delete(dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println("Deleting file: "+file); Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { System.out.println(exc.toString()); return FileVisitResult.CONTINUE; } }); } }
Sample Output
Deleting recursivey : E:\tmp\java\tutorial\nio\file\delete Deleting file: E:\tmp\java\tutorial\nio\file\delete\sample doc.txt Deleting file: E:\tmp\java\tutorial\nio\file\delete\sub dir\source code.au3 deleting directory :E:\tmp\java\tutorial\nio\file\delete\sub dir deleting directory :E:\tmp\java\tutorial\nio\file\delete\sub1 Deleting file: E:\tmp\java\tutorial\nio\file\delete\test.pub deleting directory :E:\tmp\java\tutorial\nio\file\delete