gpt4 book ai didi

java函数读取文件夹中的文件

转载 作者:行者123 更新时间:2023-12-01 14:47:26 24 4
gpt4 key购买 nike

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

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

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

最佳答案

您将需要获取文件夹路径,然后循环遍历该文件夹中的所有文件,并进行检查以过滤掉您不需要的文件。

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
}
}
}

关于java函数读取文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15281930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com