2012-06-28 78 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. 
}