【问题标题】:How to count the lines of code of multiple files in a directory?如何统计一个目录中多个文件的代码行数?
【发布时间】:2020-04-08 11:37:33
【问题描述】:

我有 10 个 Java 测试用例文件保存在一个目录中。文件夹结构是这样的,

Test Folder
 test1.java
 test2.java
 .
 .
 etc. 

在每个文件中,都有不同的 Java 单元测试用例。

比如test1.java是这样的,

@Test
public void testAdd1Plus1() 
{
    int x  = 1 ; int y = 1;
    assertEquals(2, myClass.add(x,y));
}

我想计算这个“测试文件夹”目录中每个文件的行数,并将每个文件的行数保存在一个名为“testlines”的单独目录中

例如,“testlines”目录结构如下所示,

testlines
 test1.java
 test2.java
 .
 .
 etc.

“testlines”目录下的test1.java 的内容应该是5,因为Test Folder 目录下的test1.java 有五行代码。

如何编写 Java 程序来达到这个标准?

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: java nlp lines-of-code


【解决方案1】:

您需要遍历每个文件,读取计数,在目标目录中创建一个新文件并将该计数添加到其中。

下面是一个工作示例,假设您只扫描一个级别的文件。如果你想要更多的关卡,你可以。

此外,路径分隔符取决于您运行代码的平台。我在 Windows 上运行了这个,所以使用了\\。如果您使用的是 Linux 或 Mac,请使用/

import java.io.*;
import java.util.*;

public class Test {

    public static void main(String[] args) throws IOException  {
        createTestCountFiles(new File("C:\\Test Folder"), "C:\\testlines");
    }

    public static void createTestCountFiles(File dir, String newPath) throws IOException {

        File newDir = new File(newPath);
        if (!newDir.exists()) {
            newDir.mkdir();
        }

        for (File file : dir.listFiles()) {
            int count = lineCount(file.getPath());
            File newFile = new File(newPath+"\\"+file.getName());
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            try (FileWriter fw = new FileWriter(newFile)) {
                fw.write("" + count + "");
            }
        }
    }

    private static int lineCount(String file) throws IOException  {
        int lines = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))){
            while (reader.readLine() != null) lines++;
        }
        return lines;
    }
}

【讨论】:

  • 文件未在 testlines 文件夹中创建。我试图打印出路径,路径看起来像这样,/home/mypath/folder/testlines\test1.java
  • 文件名前似乎有一个反斜杠,因此它没有创建文件
  • 您的第 23 行应改为“/”而不是“\\”
猜你喜欢
  • 1970-01-01
  • 2012-04-01
  • 2018-11-20
  • 1970-01-01
  • 2016-02-19
  • 2017-07-13
  • 2014-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多