How to delete a folder with files using Java

后端 未结 28 3563
北荒
北荒 2020-11-28 05:36

I want to create and delete a directory using Java, but it isn\'t working.

File index = new File(\"/home/Work/Indexer1\");
if (!index.exists()) {
    index.m         


        
28条回答
  •  悲&欢浪女
    2020-11-28 06:10

    I like this solution the most. It does not use 3rd party library, instead it uses NIO2 of Java 7.

    /**
     * Deletes Folder with all of its content
     *
     * @param folder path to folder which should be deleted
     */
    public static void deleteFolderAndItsContent(final Path folder) throws IOException {
        Files.walkFileTree(folder, 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 {
                if (exc != null) {
                    throw exc;
                }
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    

提交回复
热议问题