统计你写的java代码行数

本文介绍了一个用于统计Java源代码中代码行数、注释行数及空行数的小工具。该工具通过遍历指定目录下的所有Java文件,并利用正则表达式来区分不同类型的行。此外,还提供了一个示例,展示如何使用此工具统计特定目录下的Java文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.youkuaiyun.com/suwanjun881011/article/details/4475967

  1. importjava.io.BufferedReader;
  2. importjava.io.File;
  3. importjava.io.FileNotFoundException;
  4. importjava.io.FileReader;
  5. importjava.io.IOException;
  6. /**
  7. *
  8. *@authorjun
  9. *
  10. */
  11. publicclassSumJavaCode{
  12. staticlongnormalLines=0;//空行
  13. staticlongcommentLines=0;//注释行
  14. staticlongwhiteLines=0;//代码行
  15. publicstaticvoidmain(String[]args){
  16. SumJavaCodesjc=newSumJavaCode();
  17. Filef=newFile("D://spring-framework-2.0-with-dependencies//spring-framework-2.0");
  18. System.out.println(f.getName());
  19. sjc.treeFile(f);
  20. System.out.println("空行:"+normalLines);
  21. System.out.println("注释行:"+commentLines);
  22. System.out.println("代码行:"+whiteLines);
  23. }
  24. /**
  25. *查找出一个目录下所有的.java文件
  26. *
  27. *@paramf要查找的目录
  28. */
  29. privatevoidtreeFile(Filef){
  30. File[]childs=f.listFiles();
  31. //intcount=0;
  32. //intsum=0;
  33. for(inti=0;i<childs.length;i++){
  34. //System.out.println(preStr+childs[i].getName());
  35. if(!childs[i].isDirectory()){
  36. if(childs[i].getName().matches(".*//.java$")){
  37. System.out.println(childs[i].getName());
  38. //count++;
  39. sumCode(childs[i]);
  40. }
  41. }else{
  42. treeFile(childs[i]);
  43. //sum+=count;
  44. }
  45. }
  46. }
  47. /**
  48. *计算一个.java文件中的代码行,空行,注释行
  49. *
  50. *@paramfile
  51. *要计算的.java文件
  52. */
  53. privatevoidsumCode(Filefile){
  54. BufferedReaderbr=null;
  55. booleancomment=false;
  56. try{
  57. br=newBufferedReader(newFileReader(file));
  58. Stringline="";
  59. try{
  60. while((line=br.readLine())!=null){
  61. line=line.trim();
  62. if(line.matches("^[//s&&[^//n]]*$")){
  63. whiteLines++;
  64. }elseif(line.startsWith("/*")&&!line.endsWith("*/")){
  65. commentLines++;
  66. comment=true;
  67. }elseif(true==comment){
  68. commentLines++;
  69. if(line.endsWith("*/")){
  70. comment=false;
  71. }
  72. }elseif(line.startsWith("//")){
  73. commentLines++;
  74. }else{
  75. normalLines++;
  76. }
  77. }
  78. }catch(IOExceptione){
  79. e.printStackTrace();
  80. }
  81. }catch(FileNotFoundExceptione){
  82. e.printStackTrace();
  83. }finally{
  84. if(br!=null){
  85. try{
  86. br.close();
  87. br=null;
  88. }catch(IOExceptione){
  89. e.printStackTrace();
  90. }
  91. }
  92. }
  93. }
  94. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值