JAVA uses the IO stream to see how many lines of program it has written
As a novice who has been in JAVA for a while, I believe many students have the idea of checking how many lines of code they have written. This article uses a simple IO stream to achieve this function:
Main principle :
Using the **readLine()** method of the buffered stream BufferedReader , you can read line by line (but this method does not recognize line breaks, so the total number of output lines does not include blank lines).
code show as below:
import org.junit.Test;
import java.io.*;
public class Test {
int count;
// 测试Java工作区代码的行数
@Test
public void test() {
File firstFile = new File("d:/JAVA工作区"); // 这里放的是Java工作区(workplace)的文件目录,就是eclipse或者IDEA的工作区目录
System.out.println(func(firstFile));
}
// 求行数的函数
public int func(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (var i = 0; i < files.length; i++) {
func(files[i]);
}
} else {
if (file.getName().endsWith(".java")) {
BufferedReader br = null;
try {
FileReader fr = new FileReader(file);
br = new BufferedReader(fr);
int len;
char[] cbuf = new char[20];
while ((len = br.read(cbuf)) != -1) {
String str = br.readLine();
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return count;
}
}
I am also a JAVA novice. I hope you can give me your advice and leave a message to write down the deficiencies or improvements in this article. Thank you! ! !