2015年12月31日 星期四

Java - 列印所有程式程式碼行數

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ScanCode {
public static void main(String args[]) {
ScanCode scanCode = new ScanCode();

final File folder = new File("C:\\workspace\\android\\src");
scanCode.listFilesForFolder(folder);
}

public void listFilesForFolder(final File folder) {
   for (final File fileEntry : folder.listFiles()) {
       if (fileEntry.isDirectory()) {
           listFilesForFolder(fileEntry);
       } else {
        try {
        System.out.println(folder.getAbsolutePath() + "\t" + fileEntry.getName() + "\t" +countLines(fileEntry.getAbsolutePath()));
        } catch(Exception ex) {
        ex.printStackTrace();
        }
       }
   }
}

public int countLines(String filename) throws IOException {
   InputStream is = new BufferedInputStream(new FileInputStream(filename));
   try {
       byte[] c = new byte[1024];
       int count = 0;
       int readChars = 0;
       boolean empty = true;
       while ((readChars = is.read(c)) != -1) {
           empty = false;
           for (int i = 0; i < readChars; ++i) {
               if (c[i] == '\n') {
                   ++count;
               }
           }
       }
       return (count == 0 && !empty) ? 1 : count;
   } finally {
       is.close();
   }
}

}

沒有留言:

張貼留言