2012-07-01 66 views
-4

行修改了代碼,這時候目標數的代碼行是完美的下面是一段代碼..關於代碼

/** 
    * @param args 
    * @throws FileNotFoundException 
    */ 
    private static int totalLineCount = 0; 
    private static int totalFileScannedCount = 0; 

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

     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;lineCount++) { //saral 
         ; 


        }*/ 


        while (scanner.hasNextLine()) { 
          String line = scanner.nextLine().trim(); 
          if (!line.isEmpty()) { 
           System.out.println("debug-->"+line); // to debug cross checked that no whitespaces are there 
          lineCount++; 
          } 
        } 

        result.put(file, lineCount); 
        totalLineCount += lineCount;        
       } catch (NoSuchElementException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

    } 

    /** 
    * 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); 
     } 
    } 

但問題是,當它顯示在控制檯上的結果它拋出以下異常,請告知如何從

***************************************** 
FILE NAME FOLLOWED BY LOC 
***************************************** 
C:\Users\vaio\Desktop\Demo\fg\src\asd\abv.java ==> 9 
***************************************** 
SUM OF FILES SCANNED ==> 1 
SUM OF ALL THE LINES ==> 9 
Exception while removing reference: java.lang.InterruptedException 
java.lang.InterruptedException 
    at java.lang.Object.wait(Native Method) 
    at java.lang.ref.ReferenceQueue.remove(Unknown Source) 
    at java.lang.ref.ReferenceQueue.remove(Unknown Source) 
    at sun.java2d.Disposer.run(Unknown Source) 
    at java.lang.Thread.run(Unknown Source) 
+2

我給你的第一個忠告是重構你的代碼是更小的方法。 –

+0

克服這個錯誤我已經刪除了e.printstack跟蹤語句 –

回答

0

你有

totalLineCount += lineCount; 

在catch塊,但try塊內我看不到任何會導致NoSuchElementException異常被拋出。將catch塊代碼移動到try塊,該代碼似乎不適合作爲exceptio處理程序。至少如果你仍然想要執行它,即使發生異常,也要把它放在finally塊中。

1

克服的問題是,你正在更新的totalLineCountcatch塊內。把它移到外面。

  } catch (NoSuchElementException e) { 
       result.put(file, lineCount); // <-- 
       totalLineCount += lineCount; // <-- 
      } 

   result.put(file, lineCount); 
       totalLineCount += lineCount; 
      } catch (NoSuchElementException e) { 
       e.printStackTrace(); 
      } 
0

當NoSuchElement異常發生時,您才更新totalLineCount。您應該將它移動到try catch語句之外或放在finally塊中。

0

我已經修改了你的代碼,試圖瞭解我做了什麼,使你的代碼與工作

public class LineCount{ 
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); 
      result = 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 Map<File, Integer> getFileLineCount(final Map<File, Integer> result, final File file) 
     throws FileNotFoundException { 


    if (file.isFile()) { 
      Scanner scanner = new Scanner(new FileReader(file)); 
      int lineCount = 0; 
      // totalFileScannedCount ++; //saral 
      try { 
       /*for (lineCount = 0; scanner.nextLine() != null;) { //saral 
        ; 


       }*/ 


       while (scanner.hasNextLine()) { 
         String line = scanner.nextLine().trim(); 
         if (!line.isEmpty()) { 
          System.out.println("debug-->"+line); // to debug cross checked that no whitespaces are there 
         lineCount++; 
         } 
       } 


      } catch (NoSuchElementException e) { 


      } 
      result.put(file, lineCount); 
      totalLineCount += lineCount; 
     } 
    return result; 
    } 

//} 

/** 
* 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(new FilenameFilter() { 

     public boolean accept(final File directory, final String name) { 
      if (name.endsWith(".java")) { 
       return true; 
      } else { 
       return false; 
      } 
     } 
    }); 


    List<File> filesDirs = Arrays.asList(filesAndDirs); 

    for (File file : filesDirs) { 
     if (file.isFile()) { 
      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); 
    } 
} 

} 

我把上面的java文件的文件夾中,並運行此代碼 - 結果如下: -


文件名後加LOC


/家/hkr/Desktop/LineCount.java ==> 129掃描文件==的


SUM> 1個 SUM所有的線==> 129

+0

請問你能否更新正確的代碼併發布它會使理解更加清晰,多謝更新 –

+0

也試過更新if(file.isDirectory() ){//這個必須是isFile(),不是isfile()的目錄,但會拋出錯誤 –

+0

給我一分鐘,我會發布代碼 –