Java如何確定一個目錄是否為空?

2019-10-16 22:29:38

在Java程式中,如何確定一個目錄是否為空?

以下範例使用File類的file.isDirectory()file.list()file.getPath()方法獲取目錄的大小。

package com.yiibai;

import java.io.File;

public class EmptyDirectory {
    public static void main(String[] args) {
        String dir = "F:/worksp/javaexamples/java_directories/dir11";
        File file = new File(dir);
        if (file.isDirectory()) {
            String[] files = file.list();
            if (files.length > 0) {
                System.out.println("The " + file.getPath() + " is not empty!");
                for(String str : files){
                    System.out.println("Exsits file: " + str);
                }
            }else{
                System.out.println("The " + file.getPath() + " is empty!");
            }

        }
    }
}

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

The F:\worksp\javaexamples\java_directories\dir11 is not empty!
Exsits file: dir12
Exsits file: file1 - 副本.txt
Exsits file: file1.txt