How to delete a folder with files using Java

后端 未结 28 3605
北荒
北荒 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:00

    This works, and while it looks inefficient to skip the directory test, it's not: the test happens right away in listFiles().

    void deleteDir(File file) {
        File[] contents = file.listFiles();
        if (contents != null) {
            for (File f : contents) {
                deleteDir(f);
            }
        }
        file.delete();
    }
    

    Update, to avoid following symbolic links:

    void deleteDir(File file) {
        File[] contents = file.listFiles();
        if (contents != null) {
            for (File f : contents) {
                if (! Files.isSymbolicLink(f.toPath())) {
                    deleteDir(f);
                }
            }
        }
        file.delete();
    }
    

提交回复
热议问题