Java 如何计算目录中多个文件的代码行数?
我有10个Java测试用例文件保存在一个目录中。文件夹结构如下所示Java 如何计算目录中多个文件的代码行数?,java,nlp,loc,Java,Nlp,Loc,我有10个Java测试用例文件保存在一个目录中。文件夹结构如下所示 Test Folder test1.java test2.java . . etc. @Test public void testAdd1Plus1() { int x = 1 ; int y = 1; assertEquals(2, myClass.add(x,y)); } testlines test1.java test2.java . . etc. 在每个文件中,都有不同的
Test Folder
test1.java
test2.java
.
.
etc.
@Test
public void testAdd1Plus1()
{
int x = 1 ; int y = 1;
assertEquals(2, myClass.add(x,y));
}
testlines
test1.java
test2.java
.
.
etc.
在每个文件中,都有不同的Java单元测试用例
例如,test1.java如下所示
Test Folder
test1.java
test2.java
.
.
etc.
@Test
public void testAdd1Plus1()
{
int x = 1 ; int y = 1;
assertEquals(2, myClass.add(x,y));
}
testlines
test1.java
test2.java
.
.
etc.
我想计算这个“testfolder”目录中每个文件的行数,并将每个文件的行数保存在一个名为“testlines”的单独目录中
例如,“testlines”目录结构如下所示
Test Folder
test1.java
test2.java
.
.
etc.
@Test
public void testAdd1Plus1()
{
int x = 1 ; int y = 1;
assertEquals(2, myClass.add(x,y));
}
testlines
test1.java
test2.java
.
.
etc.
“testlines”目录的test1.java的内容应该是5,因为Test文件夹目录中的test1.java有五行代码
如何编写Java程序来达到这个标准 您需要检查每个文件,读取计数,在目标目录中创建一个新文件,并将该计数添加到其中 下面是一个工作示例,假设您只扫描一个级别的文件。如果你想升级,你可以 此外,路径分隔符取决于运行代码的平台。我在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应该改为“/”而不是“\\”