Dec 12, 2008

Counting Lines of Code in Java

I searched half an hour, installed the famous metrics-plugin from sourceforge, could get it to run on some projects, but not on others. Played around, no luck. Searched for another half hour. No luck. Either you use the metrics plugin or you can your lines of source code yourself. In another half hour I wrote a simple Java program to count the lines of code, including comments. But hey, it even ignores blank lines. I was most surprised that coding was actually faster than searching.

Here is the complete code:
package de.xam.loc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public final class LOC {

public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.out.println("Usage: LOC ");
} else {
LOC loc = new LOC();
File root = new File(args[0]);
loc.countLinesOfCodeInDirectory(root);
System.out.println("Found " + loc.lines + " lines in " + loc.files
+ " files within " + root.getAbsolutePath());
}
}

private long files = 0;
private long lines = 0;

private void countLinesOfCodeInDirectory(File dir) throws IOException {
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
countLinesOfCodeInDirectory(f);
} else {
if (f.getName().endsWith(".java")) {
BufferedReader br = new BufferedReader(new FileReader(f));
String line = br.readLine();
while (line != null) {
if (!line.trim().equals("")) {
this.lines++;
}
line = br.readLine();
}
br.close();
this.files++;
}
}
}
}
}

Maybe one day this will end up in an Eclipse or Maven plugin ;-)

1 comment:

  1. hey dude....thnx 4 ur LoC prog ...it helpd me to skip da starting wrk coz i still need to modify it...keep programming ...:D

    ReplyDelete