Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
04-29 04:51
관리 메뉴

zyint's blog

코드 라인수 세는 프로그램(Java) 본문

예전글들

코드 라인수 세는 프로그램(Java)

진트­ 2008. 9. 30. 00:48

코드 라인수 세는 프로그램#

요약#

 디렉토리에 있는 파일 중 특정 확장자를 가지고 있는 파일들의 코드 라인수를 세는 프로그램. 프로그램 코딩 중 프로젝트의 총 라인수를 계산할 때 사용한다.

 

소스코드#

  1. import java.io.*;


    public class LineCounter {
     private void run(String directory, String extension) {
      File dir = new File(directory);

      if (dir.exists()) {
       int lineSum = this.processDirectory(dir, extension);
       
       System.out.println(lineSum); 
      }
      else {
       System.err.printf("%s 디렉토리는 존재하지 않습니다.", directory);
      }
     }
     
     private int processDirectory(File directory, String extension) {
      File[] files = directory.listFiles();
      
      int lineCount = 0;
      
      for (File file : files) {
       // 디렉토리인 경우. 재귀호출.
       if (file.isDirectory()) {
        lineCount += this.processDirectory(file, extension);
       }
       
       // 일반 파일인 경우.
       else {
        if (file.getName().toLowerCase().endsWith("." + extension.toLowerCase())) {
         lineCount += this.countLines(file);
        }
       }
      }
      
      return lineCount;
     }
     
     private int countLines(File file) {
      BufferedReader bufferedReader = null;
      
      try {
       bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
       
       int count = 0;
       while (bufferedReader.readLine() != null) count++;
       
       return count;
      }
      catch (FileNotFoundException ex) {
       ex.printStackTrace();
       return 0;
      }
      catch (IOException ex) {
       ex.printStackTrace();
       return 0;
      }
      finally {
       try {
        if (bufferedReader != null) bufferedReader.close();
       }
       catch (IOException ex2) {}
      }
     }

     public static void main(String[] args) {
      if (args.length != 2) {
       System.out.println("Usage: java LineCounter [디렉토리] [확장자]");
       System.exit(1);
      }
      
      LineCounter lineCounter = new LineCounter();
      lineCounter.run(args[0], args[1]);
      
      System.exit(0);
     }
    }

 

사용법#

  • LineCounter.java 파일 컴파일 하기

    • javac LineCounter.java 명령을 실행한다.
    • LineCounter.class 파일이 생성된다.

 

  • LineCounter 실행하기

    • java LineCounter 프로젝트위치 파일확장자
    • 예) java LineCounter C:\workspace\project1\ java

      • C:\workspace\project1\ 폴더 아래의 .java 확장자를 가지고 있는 모든 파일의 코드 라인수를 출력한다.

 

소스코드 다운로드#

LineCounter.java

LineCounter.class

 

소스코드 출처#

http://blog.naver.com/freessul01?Redirect=Log&logNo=100039628932

 

 

이 글은 스프링노트에서 작성되었습니다.

Comments