简体   繁体   中英

java delete directory in windows

I try to delete a directory using java,here is my code

 public static void delDirectory(String path) throws IOException {
    Path p = Paths.get(path);
    delHelp(p);
}

private static void delHelp(Path p) throws IOException {
    if (!p.toFile().exists()) {
        return;
    } else if(p.toFile().isFile()){
        log.debug("delete file:" + p.toAbsolutePath().toString());
        Files.delete(p);
    }else if(p.toFile().isDirectory()){
        for(Path subPath:Files.newDirectoryStream(p)){
            delHelp(subPath);
        }
        log.debug("delete directory:"+p.toAbsolutePath().toString());
        Files.delete(p);
    }
}

On unix-like system, it works out. On windows, the code Files.delete(p) actually move the directory to the trash can, so when delete the parent directory the code will throw exception: Exception in thread "main" java.nio.file.DirectoryNotEmptyException

Any idea about this os-dependent behavior? How can I work around this?

The actual problem is that you are not closing the DirectoryStream , which is causing the DirectoryNotEmptyException when you try to delete the directory.

From the Javadoc :

When not using the try-with-resources construct, then directory stream's close method should be invoked after iteration is completed so as to free any resources held for the open directory.

So you can either call close() on it when you are done with it, or use it in try-with-resources:

private static void delHelp(Path p) throws IOException {
    if (!p.toFile().exists()) {
        return;
    } else if(p.toFile().isFile()){
        Files.delete(p);
    } else if(p.toFile().isDirectory()){

        try (DirectoryStream<Path> ds = Files.newDirectoryStream(p)) {
            for (Path subPath : ds){
                delHelp(subPath);
            }
        }

        Files.delete(p);
    }
}

please first of all add this Jar into your project first.

Find below code works perfectly as per your requirement too.

ie work on window machine and should be not goes to trash/recycle-bin

   public static void main(String[] args) {
            try {
                delDirectory("E:\\RecursiveDataContainDirectoryName");
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        public static void delDirectory(String path) throws IOException {
                Path p = Paths.get(path);
                FileDeleteStrategy.FORCE.delete(p.toFile());
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM