java一个方法的代码行数_利用Java简单实现一个代码行数统计器方法实例

前言

哈喽,我是小黑, 最近学了java的输入输出流后一直心痒痒,总想找一点事情来做,所以用java代码来实现了一下统计代码的所有行数,看一下我上大学以来到底打了多少行。

先附上实现代码吧!

package InOutStream;

import java.util.* ;

import java.io.* ;

class codeCount {

private static int count ; //统计总行数

private static int countCPP ;//CPP

private static int countJAVA ;//java

private static int countPY ;//python

private String path ; //用于接收用户输入保存代码的文件夹的路径

private int reading(String path) throws Exception { //该函数用来统计一个代码文件的行数

FileReader reader = new FileReader(path) ;

BufferedReader buffer = new BufferedReader(reader) ;

int count = 0 ;

while(buffer.readLine()!=null) {

count ++ ;

}

buffer.close() ;

reader.close() ;

return count ;

}

private void caculate(String nowpath) throws Exception{//计数函数

File nowfile = new File(nowpath) ;

if (nowfile.isFile()) {

if (nowpath.endsWith(".cpp")) {

int sum = reading(nowpath) ;

countCPP += sum ;

count += sum ;

}

else if (nowpath.endsWith(".py")) {

int sum = reading(nowpath) ;

countPY += sum ;

count += sum ;

}

else if (nowpath.endsWith(".java")) {

int sum = reading(nowpath) ;

countJAVA += sum ;

count += sum ;

}

else {

System.out.println(nowpath.substring(nowpath.indexOf("."))+":该类型文件不属于代码文件或该代码文件统计功能正在开发中,敬请期待!");

}

}

else { //如果这个路径表示的是一个文件夹,则执行递归操作

String []filesset = nowfile.list() ;

for (String i:filesset ) {

String newpath = nowpath + nowfile.separator + i ;//合成路径

caculate(newpath) ;

}

}

}

public codeCount(String src) {

path = src ;

}

public static int getLinesCPP() {

return countCPP ;

}

public static int getLinesJAVA() {

return countJAVA ;

}

public static int getLinesPY() {

return countPY ;

}

public static int getLines() {

return count ;

}

public void caculator() throws Exception { //外界包装

this.caculate(path) ;

}

public String toString() { //重写toString方法

return "统计结果如下:

" +

"cpp行数:

"+countCPP +

"

java行数:

"+countJAVA +

"

python行数:

"+countPY ;

}

}

public class Count{

public static void main(String []args) throws Exception {

Scanner cin = new Scanner(System.in) ;

System.out.println("请输入地址:");

String path = cin.next() ;

codeCount machine = new codeCount(path) ;

machine.caculator();

System.out.println(machine.toString());

cin.close();

}

}

实例:

我在桌面保存了一个文件夹用来保存代码:

b78b8f07409292fd7431a37b9934859b.png

打开后是这个样子:

2b73954358daf39a3167d4e9a371dbc4.png

取路径:

fceb6a75e9547119b2658598b8f0d25b.png

运行程序,将路径粘贴到程序之内

d5994e3579100fbb858e9d72e9141c4d.png

结果如下!!!

3f990c972c33fea6fad0b573977d55a9.png

这就是所有代码拉!!如果你有其他什么实现方法或者意见或者建议,欢迎在评论区中提出来哦!

ps:由于我只学了c、cpp、java、python。所以代码中只针对这几种进行了统计,欢迎您修改代码来满足您的需求!!

总结

到此这篇关于利用Java简单实现一个代码行数统计器的文章就介绍到这了,更多相关Java实现代码行数统计器内容请搜索云海天教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持云海天教程!

原文链接:https://blog.csdn.net/Li_black/article/details/109558603

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值