public static void main(String[] args) { String filePath = "/Volumes/DATA/xxxxx"; File rootFile = new File(filePath); System.out.println( "計:"+countFile(rootFile, "java", true) + " 個文件,共 " +countFile(rootFile, "java", false)+" 行!"); } private static int countFile(File rootFile, String suffix, boolean countLine){ int result = 0; File[] childFiles = rootFile.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory() || pathname.getAbsolutePath().endsWith(suffix); } }); for (File f : childFiles) { if (f.isFile()) { int lineCount = getFileLinesCount(f); // System.out.println(f.getAbsolutePath()+" "+lineCount); if (countLine) { result += lineCount; } else { result++; } } else { result += countFile(f, suffix, countLine); } } return result; } private static int getFileLinesCount(File file) { if (file == null || file.isDirectory()) return 0; BufferedReader br = null; int result = 0; try { br = new BufferedReader(new FileReader(file)); while (br.readLine() != null) { result ++; } } catch (IOException e) { e.printStackTrace(); } finally{ if (br != null) { try { br.close(); } catch (IOException e2) { } } } return result; }