编写程序,使用递归方法,实现统计项目目录下有多个java文件,共有多少行代 ...

打印 上一主题 下一主题

主题 856|帖子 856|积分 2568

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. /**
  4. * @author Mxhlin
  5. * @Email fuhua277@163.com
  6. * @Date 2022/09/21/14:55
  7. * @Version
  8. * @Description
  9. */
  10. public class Count {
  11.     static int  num=0;
  12.     static int  rows=0;
  13.     public static void main(String[] args) {
  14.         count(new File("D:\\peixun\\java\\Lx"));
  15.         System.out.println("=========================================");
  16.         System.out.println("共有"+num+"个java文件");
  17.         System.out.println("共有"+rows+"行");
  18.     }
  19.     public static void count(File src){
  20.         if (src.isDirectory()){
  21.             File[] files = src.listFiles();
  22.             for (File file : files) {
  23.                 if (file.isDirectory()) count(file);
  24.                 if (file.isFile() && file.getName().endsWith(".java")){
  25.                     ++num;
  26.                     rows+=getFileRows(file);
  27.                     System.out.printf("文件:%s(%d行)。%n",file.getAbsolutePath(),getFileRows(file));
  28.                 }
  29.             }
  30.         }
  31.     }
  32.     public static int getFileRows(File src){
  33.         int rows = 0;
  34.         try (FileInputStream fis = new FileInputStream(src)){
  35.             rows = (int)new String(fis.readAllBytes()).lines().count();
  36.         }catch (Exception e){
  37.         }
  38.         return rows;
  39.     }
  40. }
复制代码
代码分析
代码的作用是在指定文件夹下找到有多少.java文件,每个java文件又有多少行代码,一共写了多少代码
大家可以使用这个代码来查看自己写了多少代码。注意文件路径一定要对!
写了两个方法分别是getFileRowscount
getFileRows使用FileInputStream文件输入字符流,使用randAllBytes()方法获取文件的所有字节,转化为字符串,获取lines()行和count()计数。转换为int类型,方便计数。最后返回行数!
count遍历所有文件。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

半亩花草

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表