我有一個程序,當前讀取文件,查找關鍵字,並輸出關鍵字的出現次數。我需要編寫一個讀入所有文件的函數,並且我需要將該函數插入到一個點中,以便顯示出現的總次數。Java函數讀取文件的文件夾
我目前正在讀1個文件中像這樣
try (BufferedReader br = new BufferedReader(new FileReader("C:\\P4logs\\out.log.2012-12-26")))
{
我有一個程序,當前讀取文件,查找關鍵字,並輸出關鍵字的出現次數。我需要編寫一個讀入所有文件的函數,並且我需要將該函數插入到一個點中,以便顯示出現的總次數。Java函數讀取文件的文件夾
我目前正在讀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
}
}
}
我得到.listFile的錯誤它說它是undefined – user2007843 2013-03-07 21:34:20
@ user2007843 wups它的listFiles()輸入得太快 – Aboutblank 2013-03-07 21:35:09
我認爲這有效,我想我應該手動檢查日誌文件。 – user2007843 2013-03-07 21:44:37
很簡單:
File folder = new File("C:/path_to_your_folder/");
for (File file : folder.listFiles()) {
// Got a file. Do what you want.
}
你需要一個遞歸函數的遞歸搜索
void readAllFiles(final File myFile) {
if(file.isFile()) {
//read the file and whatever
return;
}
for(final File childFile : myFile.listFiles()) {
readAllFiles(childFile);
}
}
你的意思是讀一個文件夾中的所有文件,在一個陣列讀取所有文件,或創建將與任何文件進行操作的功能? – EAKAE 2013-03-07 21:24:15
你想遞歸地做這件事嗎? – 2013-03-07 21:28:30
@ bmorris591是的,我認爲這將是遞歸 – user2007843 2013-03-07 21:32:56