/** * Calculates the lines of code/comments for Java projects. * Run in the current folder. * If there are no source code files in the current folder, it will go through subfolders * Considers multi-line comments, empty lines etc. * @author Alex Rass * www.itbsllc.com */ import java.io.*; class CodeTell { private int codeLines = 0, commentLines = 0, fileCount = 0, folderCount = 0, characterCount = 0; long totalFileLength = 0; private void calcFile (File file) { BufferedReader freader; String fname, line; boolean insideComment; fname = file.getName(); if ( fname==null ) { System.out.println("Somehow the filename was null!"); } else if ( fname.toLowerCase().endsWith(".java") || fname.toLowerCase().endsWith(".idl") || fname.toLowerCase().endsWith(".rb") ) { totalFileLength+=file.length(); fileCount++; try { freader = new BufferedReader (new FileReader (file)); System.out.println(" "+fname); line = freader.readLine(); if ( line!=null ) line = line.trim(); insideComment = false; int temp; while ( line!=null ) { characterCount+=line.length(); if ( line.length() == 0 ) { // ignore those } else if ( insideComment ) { if ( (temp = line.indexOf("*/")) >= 0 ) { insideComment = false; if ( line.length() > temp ) codeLines++; if ( temp > 2 ) commentLines++; } } else { if ( !line.startsWith("//") ) codeLines++; if ( line.startsWith("/*") ) insideComment = true; if ( line.indexOf("//") >= 0 ) commentLines++; } line = freader.readLine(); if ( line!=null ) { line = line.trim(); } } } catch ( FileNotFoundException e ) { System.out.println("File not found: " + fname); } catch ( Exception e ) { System.out.println(e); e.printStackTrace(); } } // if } public static void main (String[] args) { (new CodeTell()).start(); } // main public void start() { File folder = new File("."); examineList(folder.listFiles()); System.out.println("Folders:\t"+folderCount); System.out.println("Files:\t\t"+fileCount); System.out.println("Code:\t\t"+codeLines+" lines"); System.out.println("Comments:\t"+commentLines+" lines"); System.out.println("Combined:\t"+characterCount+" characters"); System.out.println("File Size:\t"+totalFileLength+" bytes"); System.out.println(""); } protected void examineList(File[] files) { // do files first for ( int i=0; i < files.length; i++ ) { // go through all files if (! files[i].isDirectory() ) calcFile (files[i]); } // do folders after - looks better when they are grouped separately. for ( int i=0; i < files.length; i++ ) {// go through all folders. if ( files[i].isDirectory() ) { System.out.println(files[i].getName()); folderCount++; examineList (files[i].listFiles()); } } } //examineList } // class CodeTell