package com; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.Pattern; public class CodeCounter { static final String regex = "^\\S+\\.(?i)(h|cpp|c|hpp)$"; static final Pattern pattern = Pattern.compile(regex); static int count = 0; public static final boolean isCodeFile(String fileName) { return pattern.matcher(fileName).matches(); } public static void main(String[] args) { String rootDir = "C:/Users/Administrator/Desktop/WlyTool"; FindDirectory(rootDir); System.out.println("代码总行数:" + count); } public static void FindDirectory(String root) { // root是根目录的绝对路径 File directory = new File(root); if (!directory.exists()) return; File[] files = directory.listFiles(); // 根目录为空 for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { // 根目录的子文件夹就是要删除的文件夹 FindDirectory(files[i].getAbsolutePath()); } else if (isCodeFile(files[i].getName())) { // 文件 int nCount = getCount(files[i]); count += nCount; System.out.println("文件:" + files[i].getAbsolutePath() + " 代码总行数:" + nCount); } } } private static int getCount(File file) { int count = 0; try { FileInputStream fis = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(fis); BufferedReader bReader = new BufferedReader(reader); String line = bReader.readLine(); while (line != null) { count++; line = bReader.readLine(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return count; } }
本文链接:https://it72.com:4443/2958.htm