首先,我正在寻找问题的答案,但我找不到确切的答案。 所以我在不同的文件夹和子文件夹中有许多.log文件(文本文档)。我在不同的文件夹中有很多很多.log文件。如果它们是三个关键字之一,则我希望完整的行符合以下条件:一个单独的文本文档:
我知道我的代码尚未完成,但是我不知道如何继续。
如果我运行代码,我会看到字母之间总是空白。为什么?
感谢所有有用的答案!
public static void main(String[] args) {
// declare folder
File folder = new File("path");
if (!folder.exists()) {
System.out.println("folder not existing");
}
listAllFilesForFolder(folder);
}
public static void listAllFilesForFolder(File folder) {
// for each file in folder
for (File fileEntry : folder.listFiles()) {
// if file is another folder
if (fileEntry.isDirectory()) {
// step into that folder recursively
listAllFilesForFolder(fileEntry);
} else {
// its a file
String filePath = fileEntry.getAbsolutePath();
System.out.println("File is: " + filePath);
parseFile(filePath);
}
}
}
public static void parseFile(String file) {
BufferedReader reader;
try {
int LineCount = 0;
// String line1 = "";
reader = new BufferedReader(new FileReader(file));
File folderError = new File("ErrorFolder");
PrintWriter out = new PrintWriter("filename1.txt");
// for each line in file
String line = reader.readLine();
while (line != null) {
folderError.mkdir(); // create a folder in your current work space
LineCount++;
// print line
System.out.println("line is: " + LineCount + " " + line);
// TODO if line has an error, ... do something
// read next line
line = reader.readLine();
out.println(line);
}
out.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
如果您使用org.apache.commons.io.FileUtils进行以下操作:
package com.test;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import java.io.BufferedReader;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
public class SearchInFilesAndDirectory {
private static int lineNumber = 0;
private static final String FOLDER_PATH = "path_to_file";
public static void main(String[] args) {
File dir = new File(FOLDER_PATH);
List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, DirectoryFileFilter.DIRECTORY);
for (File file : files) {
if (file.isFile()) {
try (BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
String line;
while ((line = br.readLine()) != null) {
lineNumber++;
if (line.contains("word")) {
System.out.println("Keyword found in " + file.toPath() + " at line " + lineNumber + ".\n" + line.trim());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
上面将打印出路径和行号,即
Keyword found in /path/test/childFolder/test.txt at line 3.
3 Keyword test
Keyword found in /path/test/testFile.txt at line 5.
1 keyword ----