java獲取一個目錄下的所有的文件或文件夾名稱

public static void main(String[] args) {
    testFileDirOrName("你的項目路徑");
}

private static void testFileDirOrName(String path) {
    File dirFile = new File(path);
    if (dirFile.exists()) {
        File[] files = dirFile.listFiles();
        if (files != null) {
            for (File fileChildDir : files) {
                //輸出文件名或者文件夾名
                System.out.print(fileChildDir.getName());
                if (fileChildDir.isDirectory()) {
                    System.out.println(" :  此爲目錄名");
                    //通過遞歸的方式,可以把目錄中的所有文件全部遍歷出來
                    testFileDirOrName(fileChildDir.getAbsolutePath());
                }
                if (fileChildDir.isFile()) {
                    System.out.println(" :  此爲文件名");
                }
            }
        }
    }else{
        System.out.println("你想查找的文件不存在");
    }
}
測試結果如下:

.classpath :  此爲文件名
.idea :  此爲目錄名
encodings.xml :  此爲文件名
kotlinc.xml :  此爲文件名
libraries :  此爲目錄名
bss.xml :  此爲文件名
ehcache.xml :  此爲文件名
hdiv.xml :  此爲文件名
ibatis_2_3_2.xml :  此爲文件名
j2ee.xml :  此爲文件名
jakarta_commons.xml :  此爲文件名
lib.xml :  此爲文件名
ojdbc14.xml :  此爲文件名
poi_3_0_alpha2_20060616.xml :  此爲文件名

。。。。。。。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章