chance
In the interview yesterday, I was asked how many lines of code have I written? I don't know how to answer for a while, and I don't have a concept, because I have never counted the number of lines of code!
After the interview, I thought about counting
accomplish
.java
In fact, it is not difficult to implement. We only need to sum the number of lines of all files ending in the specified directory . Here, depth-first traversal is used for statistics. The code is as follows:
import java.io.*;
import java.util.Scanner;
/**
* @program: leetCode
* @description: 求某个目录下的java代码有多少行
* @author: liangjiayy
* @create: 2022-09-29 21:40
**/
public class SumOfCodeLineCount {
/**
* 要统计的文件的后缀名
*/
private static final String SUFFIX = ".java";
public static void main(String[] args) {
//定义起始目录
String dir = "C:\\Users\\AikeTech\\IdeaProjects\\";
System.out.println("你要统计的起始目录是:\"" + dir + "\",确定请输入\"Y\":");
String input = new Scanner(System.in).nextLine();
if (!"y".equalsIgnoreCase(input.trim())) {
System.out.println("你已取消统计!");
return;
}
//获取该目录下所有java代码的行数
long lineCount = getLineCount(dir);
System.out.println("\"" + dir + "\"目录下,后缀为\"" + SUFFIX + "\"的代码共有 " + lineCount + " 行!");
}
/**
* 获取某个目录下,所有后缀名为 SUFFIX(类变量) 的文件的行数
*
* @param dir
* @return
*/
private static long getLineCount(String dir) {
File file = new File(dir);
if (!file.isDirectory()) {
//是个文件,统计有多少行
if (dir.endsWith(SUFFIX)) {
return statisticalLineCount(file);
}
return 0;
}
//是个目录,递归
String[] list = file.list();
if (list == null) {
return 0;
}
long sum = 0;
for (String l : list) {
//父目录 + 分隔符 + 文件/目录名
sum += getLineCount(dir + "\\" + l);
}
return sum;
}
/**
* 统计某个文件的行树
*
* @param file
* @return
*/
private static long statisticalLineCount(File file) {
try (LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(file))) {
long length = file.length();
lineNumberReader.skip(length);
return lineNumberReader.getLineNumber();
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
}
operation result:
use
How to use the above class?
-
If you also want to count the number of lines of all java codes in a certain directory, just modify dir in the above code: it will find the number of lines of all files ending with .java in this directory
-
If you count the number of lines in other files, you also need to modify the following variables (suffix name)