2012-06-28 31 views
0

我開發了一個java代碼,用於從用戶選擇的文件夾中讀取java文件。它顯示每個文件中有多少行代碼,它只讀取.java文件,最終結果顯示在控制檯上,但是我想到了一種情況,比如我有一個文件夾,其中根本沒有文件,或者存在在這種情況下,沒有.java文件的文件夾我想通過捕獲異常來顯示定製的消息,並顯示消息文件夾中沒有.java文件,請告知如何實現這一點..下面是我的作品的代碼..關於在java中捕捉異常

public static void main(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<String, Integer> result = new HashMap<String, Integer>(); 
      File directory = new File(chooser.getSelectedFile().getAbsolutePath()); 
      int totalLineCount = 0; 
      File[] files = directory.listFiles(new FilenameFilter(){ 
        @Override 
        public boolean accept(File directory, 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; 
        try 
        { for (lineCount = 0; scanner.nextLine() != null; lineCount++) ; 
          } catch (NoSuchElementException e) 
        { result.put(file.getName(), lineCount); 
        totalLineCount += lineCount; 
            } 


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

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

      }  

    } 

回答

4

你並不需要使用異常,數組文件中有文件,所有你需要的是檢查其大小條件語句。

if(files.length == 0) { 
    //Do whatever you like to inform the user there are no java files in the directory. 
}