0

ユーザーが選択したフォルダーから Java ファイルを読み取る Java コードを開発しました。各ファイルに含まれるコードの行数が表示され、 .java ファイルのみが読み取られ、最終結果が console に表示されますが、ファイルがまったくない、またはあるフォルダーがあるとしましょう。そのような場合に.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

1 に答える 1

4

例外を使用する必要はありません。配列ファイルにはファイルが含まれています。必要なのは、そのサイズをチェックする条件ステートメントだけです。

if(files.length == 0) {
    //Do whatever you like to inform the user there are no java files in the directory.
}
于 2012-06-28T18:22:54.207 に答える