从文件夹中读取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 result = new HashMap(); File directory = new File(chooser.getSelectedFile().getAbsolutePath()); int totalLineCount = 0; File[] files = directory.listFiles(new FilenameFilter(){ @Override public boolean accept(File dir, String name) { return name.matches("\\*\\.java"); } } ); 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 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); } 

我也编辑了但是仍然没有工作请告知请告知如何只读取.java作为扩展名的文件,换句话说只有文件夹中的java文件,请指教

你需要一个FilenameFilter。 这应该适合你:

 FilenameFilter javaFileFilter= new FilenameFilter() { @Override public boolean accept(File logDir, String name) { return name.endsWith(".java") } }; 

您应该查看过滤 JFileChooser 中的文件列表 。

它有一个ImageFilter.java的例子,它只显示文件选择器中的图像文件。