我有一个程序,当前正在读取文件,查找关键字,并输出关键字的出现次数。我需要编写一个读取所有文件的函数,我需要在一个点中插入这个函数,以便显示总出现次数。
我目前正在阅读1个这样的文件
try (BufferedReader br = new BufferedReader(new FileReader("C:\\P4logs\\out.log.2012-12-26")))
{
答案 0 :(得分:1)
您需要获取文件夹路径,然后循环浏览该文件夹中的所有文件,并检查过滤掉您不想要的文件。
File path = new File(path); //path to your folder. eg. C:\\P4logs
for(File f: path.listFiles()) { // this loops through all the files + directories
if(f.isFile()) { // checks if it is a file, not a directory.
// most basic check. more checks will have to be added if
// you have other files you don't want read. (like non log files)
try (BufferedReader br = new BufferedReader(new FileReader(f.getAbsolutePath()))) {
// gets the full path of a file. so "C:\\P4logs\\out.log.2012-12-26"
//do stuff
}
}
}
答案 1 :(得分:0)
很简单:
File folder = new File("C:/path_to_your_folder/");
for (File file : folder.listFiles()) {
// Got a file. Do what you want.
}
答案 2 :(得分:0)
您需要一个递归搜索的递归函数
void readAllFiles(final File myFile) {
if(file.isFile()) {
//read the file and whatever
return;
}
for(final File childFile : myFile.listFiles()) {
readAllFiles(childFile);
}
}