[英]Reading the java files from the folder
我開發了一個應用程序,用於從用戶選擇的文件夾中讀取文件。 它顯示每個文件中有多少行代碼。 我只想在文件選擇器中顯示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 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<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);
}
我也編輯了但是仍然沒有工作請告知請告知如何只讀取.java作為擴展名的文件,換句話說只有文件夾中的java文件,請指教
它有一個ImageFilter.java的例子,它只顯示文件選擇器中的圖像文件。
你需要一個FilenameFilter。 這應該適合你:
FilenameFilter javaFileFilter= new FilenameFilter() {
@Override
public boolean accept(File logDir, String name) {
return name.endsWith(".java")
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.