Java如何刪除一個目錄?

2019-10-16 22:29:36

在Java程式中,如何如何刪除一個目錄?

以下範例演示如何使用File類的dir.isDirectory()dir.list()deleteDir()方法來刪除其檔案和子目錄後,再刪除該目錄。

package com.yiibai;

import java.io.File;

public class DeleteDirectory {
    public static void main(String[] argv) throws Exception {
        String deldir = "F:\\worksp\\javaexamples\\java_directories\\dir1";
        deleteDir(new File(deldir));
    }

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));

                if (!success) {
                    return false;
                }
            }
        }
        System.out.println("The directory is deleted.");
        return dir.delete();
    }
}

執行上面範例程式碼,得到以下結果 -

The directory is deleted.
The directory is deleted.
The directory is deleted.

註:由於dir1目錄中有兩個目錄,所以上面會多列印兩條資訊。