0

我有一个程序当前读取文件,查找关键字,并输出关键字的出现次数。我需要编写一个读取所有文件的函数,并且我需要将此函数插入​​某个位置,以便显示出现的总数。

我目前正在阅读这样的 1 个文件

try (BufferedReader br = new BufferedReader(new FileReader("C:\\P4logs\\out.log.2012-12-26")))
    {
4

3 回答 3

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
        }
    }
}
于 2013-03-07T21:21:40.757 回答
0

这很简单:

File folder = new File("C:/path_to_your_folder/");

for (File file : folder.listFiles()) {
  // Got a file. Do what you want.
}
于 2013-03-07T21:20:13.300 回答
0

您需要一个递归函数来进行递归搜索

void readAllFiles(final File myFile) {
  if(file.isFile()) {
    //read the file and whatever
    return;
  }
  for(final File childFile : myFile.listFiles()) {
    readAllFiles(childFile);
  }
}
于 2013-03-07T21:37:13.520 回答