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 : 此爲文件名 。。。。。。。