java如何打印一个单词的重复次数
我想做的是写一个单词,然后搜索该单词在哪个文件中找到,以及包含该单词的次数
例如:
单词dog出现在:
file1.html - 2
file6.hmtl - 8
file25.html - 5
目前我有这个,它只显示文件名,但不显示重复次数
欢迎任何帮助
public static void main(String[] args) throws FileNotFoundException {
File dir = new File("/Users/Adan/Desktop/Files/"); // directory = target directory.
if(dir.exists()){ // Directory exists then proceed.
Pattern p = Pattern.compile("casa"); // keyword = keyword to search in files.
ArrayList<String> list = new ArrayList<String>(); // list of files.
System.out.println("La palabra " + p + " esta dentro de estos archivos:");
for(File f : dir.listFiles()){
if(!f.isFile()){
continue;
}
try
{
FileInputStream fis = new FileInputStream(f);
byte[] data = new byte[fis.available()];
fis.read(data);
String text = new String(data);
Matcher m = p.matcher(text);
if(m.find()){
list.add(f.getName()); // add file to found-keyword list.
}
fis.close();
}
catch(Exception e){
System.out.println("\n\t Error processing file : "+f.getName());
}
}
for (String listado : list) {
System.out.println(listado);//Lista
}
} // IF directory exists then only process.
else{
System.out.println("\n Directory doesn't exist.");
}
}
}
# 1 楼答案