javanlplines-of-code

How to count the lines of code of multiple files in a directory?


I have 10 Java test case files saved in a directory. The folder structure looks like this,

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

In each of these files, there are different Java Unit Test Cases.

For example, test1.java looks like this,

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

I would like to count the number of lines in each file in this "Test Folder" directory and save the line count for each file in a separate directory called "testlines"

For example, "testlines" directory structure would look like this,

testlines
 test1.java
 test2.java
 .
 .
 etc.

The content of the test1.java of the "testlines" directory should be 5 since test1.java from the Test Folder directory has five lines of code.

How can I write a Java program to achieve this criteria?


Solution

  • You need to go through each file, read the count, create a new file in your destination directory and add that count to it.

    Below is a working example assuming you are only scanning files one level. If you wish to more levels, you can.

    Also, the path separators depend on the platform you are running the code. I ran this on windows so used \\. If you are on Linux or Mac, kindly use /

    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;
        }
    }