2012-07-01 2 views
-1

자바 프로젝트 내부의 자바 패키지에있는 파일의 수를 읽은 다음 해당 파일의 코드 줄을 예를 들어 자바로 계산하는 응용 프로그램을 개발했습니다 프로젝트에 4 개의 개별 파일이있는 패키지가있는 경우 총 파일 읽기 수는 4 개가되며 각 파일에 10 줄의 코드 줄이있는 4 개의 파일은 전체 프로젝트에서 총 40 줄의 코드가됩니다. 코드 내 조각자바 내장 메서드로 공백을 제거하고 싶습니다

 private static int totalLineCount = 0; 
     private static int totalFileScannedCount = 0; 

     public static void main(final String[] args) throws FileNotFoundException { 

      JFileChooser chooser = new JFileChooser(); 
      chooser.setCurrentDirectory(new java.io.File("C:" + File.separator)); 
      chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS"); 
      chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
      chooser.setAcceptAllFileFilterUsed(false); 
      if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
       Map<File, Integer> result = new HashMap<File, Integer>(); 
       File directory = new File(chooser.getSelectedFile().getAbsolutePath()); 

       List<File> files = getFileListing(directory); 

       // print out all file names, in the the order of File.compareTo() 
       for (File file : files) { 
        // System.out.println("Directory: " + file); 
        getFileLineCount(result, file); 
        //totalFileScannedCount += result.size(); //saral 
       } 

       System.out.println("*****************************************"); 
       System.out.println("FILE NAME FOLLOWED BY LOC"); 
       System.out.println("*****************************************"); 

       for (Map.Entry<File, Integer> entry : result.entrySet()) { 
        System.out.println(entry.getKey().getAbsolutePath() + " ==> " + entry.getValue()); 
       } 
       System.out.println("*****************************************"); 
       System.out.println("SUM OF FILES SCANNED ==>" + "\t" + totalFileScannedCount); 
       System.out.println("SUM OF ALL THE LINES ==>" + "\t" + totalLineCount); 
      } 

     } 

     public static void getFileLineCount(final Map<File, Integer> result, final File directory) 
       throws FileNotFoundException { 
      File[] files = directory.listFiles(new FilenameFilter() { 

       public boolean accept(final File directory, final String name) { 
        if (name.endsWith(".java")) { 
         return true; 
        } else { 
         return false; 
        } 
       } 
      }); 
      for (File file : files) { 
       if (file.isFile()) { 
        Scanner scanner = new Scanner(new FileReader(file)); 
        int lineCount = 0; 
        totalFileScannedCount ++; //saral 
        try { 
         for (lineCount = 0; scanner.nextLine() != null;) { 
          while (scanner.hasNextLine()) { 
    String line = scanner.nextLine().trim(); 
    if (!line.isEmpty()) { 
    lineCount++; 
    } 
         } 
        } catch (NoSuchElementException e) { 
         result.put(file, lineCount); 
         totalLineCount += lineCount; 
        } 
       } 
      } 

     } 

     /** 
     * Recursively walk a directory tree and return a List of all Files found; 
     * the List is sorted using File.compareTo(). 
     * 
     * @param aStartingDir 
     *   is a valid directory, which can be read. 
     */ 
     static public List<File> getFileListing(final File aStartingDir) throws FileNotFoundException { 
      validateDirectory(aStartingDir); 
      List<File> result = getFileListingNoSort(aStartingDir); 
      Collections.sort(result); 
      return result; 
     } 

     // PRIVATE // 
     static private List<File> getFileListingNoSort(final File aStartingDir) throws FileNotFoundException { 
      List<File> result = new ArrayList<File>(); 
      File[] filesAndDirs = aStartingDir.listFiles(); 
      List<File> filesDirs = Arrays.asList(filesAndDirs); 
      for (File file : filesDirs) { 
       if (file.isDirectory()) { 
        result.add(file); 
       } 
       if (!file.isFile()) { 
        // must be a directory 
        // recursive call! 
        List<File> deeperList = getFileListingNoSort(file); 
        result.addAll(deeperList); 
       } 
      } 
      return result; 
     } 

     /** 
     * Directory is valid if it exists, does not represent a file, and can be 
     * read. 
     */ 
     static private void validateDirectory(final File aDirectory) throws FileNotFoundException { 
      if (aDirectory == null) { 
       throw new IllegalArgumentException("Directory should not be null."); 
      } 
      if (!aDirectory.exists()) { 
       throw new FileNotFoundException("Directory does not exist: " + aDirectory); 
      } 
      if (!aDirectory.isDirectory()) { 
       throw new IllegalArgumentException("Is not a directory: " + aDirectory); 
      } 
      if (!aDirectory.canRead()) { 
       throw new IllegalArgumentException("Directory cannot be read: " + aDirectory); 
      } 
     } 

하지만 문제는, 내가 내 프로그램에서해야 할 일을 수정 알려 주시기 바랍니다 안 개별 파일에 대한 코드의 라인을 계산하는 동안 그것은 또한 공백 라인을 계산이다 그래서 그게 개별 파일의 코드 행을 계산할 때 공백을 세지 마십시오.

내 생각에 떠올랐다는 생각은 방금 읽은 문자열을 ""로 비교하고 if (! readString.trim(). equals (""))와 같이 ""(공백)이 아닌지 계산합니다. lineCount ++ 이

+0

. 그렇지 않으면 공백 만 포함하는 행은 계속 전달됩니다. – Antimony

+0

@Antimony 당신이 말한 논리로 내 코드를 업데이트 해 주시면 감사하겠습니다. –

+1

@Naresh : 당신이해야 할 일은 문자열에'trim()'을 호출하는 것입니다. 반환 된 트리밍 된 문자열을 비교에 사용합니다. 확실히 네가 먼저해볼 수 있겠 니? –

답변

2

제안에 대해 알려 주시기 바랍니다 :

  • 스캐너 사용해야 hasNextLine() 방법이있다. while 루프의 조건으로 사용합니다.
  • 그런 다음 루프 내부에서 nextLine()을 한 번 호출하여 while 루프 내부에서 줄을 가져옵니다.
  • 다시 읽어 들인 문자열에서 trim()을 호출하십시오. 최신 코드 업데이트에서 아직 귀하의 시도가 표시되지 않습니다!
  • 문자열의 메서드를 호출 할 때 핵심 개념은 해당 문자열이 변경되지 않으며 호출되는 메서드가 기본 문자열을 변경하지 않으며 trim()도 다르지 않다는 것입니다. 호출되는 String은 변경되지 않지만 문자열 으로을 되 돌린 것은이며, 실제로는 다듬은 것입니다.
  • String은 문자열을 자른 후에 호출해야하는 isEmpty() 메서드를 가지고 있습니다.

그렇게하지 않습니다

try { 
    for (lineCount = 0; scanner.nextLine() != null;) { 
     if(!readString.trim().equals("")) lineCount++; // updated one 
    } 
} catch (NoSuchElementException e) { 
    result.put(file, lineCount); 
    totalLineCount += lineCount; 
} 

대신 할 : 당신은 아마 그들을 비교하기 전에 라인을 정돈한다

int lineCount = 0; 
while (scanner.hasNextLine()) { 
    String line = scanner.nextLine().trim(); 
    if (!line.isEmpty()) { 
    lineCount++; 
    } 
} 
+0

스캐너 스캐너 = 새 스캐너 (새 FileReader (파일)); int lineCount = 0; totalFileScannedCount ++; // saral { \t/* for (lineCount = 0; scanner.nextLine()! = null; lineCount ++) {// saral ; } * 대/ \t (lineCount = 0; scanner.nextLine() = NULL;!) {// saral 동안 (! scanner.nextLine() = NULL) { \t \t }} –

+0

@ NareshSaxena : 주석에 코드를 저장할 수 없습니다. 제 대답에 편집을 참조하십시오. –

+0

.. 그게 또한 작동하지 않습니다 editied 코드를 시도했지만 실행시 모든 라인 중 일부는오고 있습니다 .. !! –

관련 문제