java当前代码行数据 java运行当前代码

如何统计某目录下的java文件代码行数可以自己写一个小程序 , 遍历每个文件;
如果是*.java就记录该文件的行数,依次累加 。
计算代码行数并测试计算某Java/C/C++源文件的代码行数GetLOC//我写了一个类 测试了一下 大致没问题 你看看吧
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
public class GetLoc {
public static void execute(String classPath) {
if (classPath == null || "".equals(classPath)) {
System.err.println("无效java当前代码行数据的类路径");
return;
}
File file = new File(classPath);
int total = 0; // 所有代码总行数
int lineCount = 0;// 有效代码总行数
int start = 0;// 多行注释开始位置
int end = 0;// 多行注释结束位置
//下面开始读取文件 按行来读 读取时候做判断
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String lineContent = br.readLine();
while (lineContent != null) {
if (lineContent == null) {
System.err.println("数据读完了!");
} else {
total++;
// 判断当前读入java当前代码行数据的记录行是否是无效行
lineContent = lineContent.trim();
lineCount++;
if ("".equals(lineContent)) {// 空行
lineCount--;
}
if (lineContent.startsWith("//")) {// 单行注释
lineCount--;
}
if (lineContent.startsWith("/*")end == 0) {// 多行注释开头
start = lineCount;
}
if ((lineContent.startsWith("*/") || lineContent
.endsWith("*/"))
start != 0) {
end = lineCount;
lineCount = lineCount - (end - start + 1);
end = 0;
start = 0;
}
}
lineContent = br.readLine();
}
br.close();// 一定要关闭资源
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 从路径中分离出类名
String temp = new StringBuffer(classPath).reverse().toString();
int sp1 = temp.indexOf("/");
int sp2 = temp.indexOf("\\");
int pos = sp1sp2 ? sp1 : sp2;//取离分隔符近的
String className = "";
if (pos != 0) {
className = temp.substring(0, pos);
className =new StringBuffer(className).reverse().toString();
}
// 拼成注释
String result = "";
if (!"".equals(className)) {
result = "//LOC(\"OneMatcher.java\") = " + lineCount;
}
// 加在类的尾巴上面
try {
RandomAccessFile randomFile = new RandomAccessFile(classPath, "rw");
long fileLength = randomFile.length();
randomFile.seek(fileLength);
randomFile.writeBytes(result);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("类文件"+className+"总共"+total+"代码,其中有效代码"+lineCount+"行");
}
public static void main(String[] args) {
execute("C:\\Users\\konglingzhen\\Desktop\\RandomAccessFile.java");
}
}
如何在Java中获取当前代码行行号和文件名如果你用的是Eclipse或MyEclipse,在代码的左边(就是有加号或减号,用于缩放代码的位置)点右键将Show Line Numbers打上对勾就可以看见行号了,文件名看包 。
Java代码中如何获文件名和行号等源码信息Java是否提供某种方法:可以让用户代码在编译时确定源码行号等信息,本人暂时不知晓 。不过从网上搜索得到的方法大致是:
Thread.currentThread().getStackTrace()[1].getFileName():获取当前文件名;
Thread.currentThread().getStackTrace()[1].getLineNumber():获取当前行号 。
其中:Thread.currentThread().getStackTrace()返回的是一个数组形式的函数调用栈(栈顶在索引0处),其中第1个元素(索引为0)为最新调用的函数信息(getStackTrace()) , 第2个元素(索引为1)为当前函数(即调用getStackTrace()的函数)信息 。

推荐阅读