java 从文件夹读取文件,从文件夹中读取Java文件

I have developed an application that reads files from the folder chosen by the user. It displays how many lines of code are in each file. I want only Java files to be shown in the file-chooser (files having .java extension). Below is my code:

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);

}

I have editied also but still it is not working please advise

please advise how to read only the files having .java as an extension in other words only java files from the folder ,please advise

解决方案

You need a FilenameFilter. This should work for you:

FilenameFilter javaFileFilter= new FilenameFilter() {

@Override

public boolean accept(File logDir, String name) {

return name.endsWith(".java")

}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值