我想制作一个能够完成以下两件事的工具::
这就是我到目前为止所得到的。 Java代码:
public String readFile(String filename) throws FileNotFoundException {
Scanner scanner = null;
File file = new File(filename);
String output = "";
try{
scanner = new Scanner(file);
}catch(FileNotFoundException e){
System.out.println("Error: File " + filename + " not found!");
}
while (scanner.hasNextLine()){
output=output+scanner.nextLine();
}
return output;
}
答案 0 :(得分:0)
因此,您要为目录中的每个文件调用readFile(file)方法。
您可以使用File.listFiles()方法获取目录中的文件列表:
File f = new File("your/directory");
File[] files = f.listFiles();
然后,您可以遍历文件(继续前面的示例):
for (File file : files) {
System.out.println(readFile(file.toString()));
}
顺便说一句,您应该使用StringBuilder附加字符串,这样就不必在每次读取新行时都创建一个新对象。
答案 1 :(得分:0)
// define method that accept `dir`, `matcher` - will be called on each file to check if file name corret or not, `consumer` - will be called on each mathed file
public static void readFiles(Path dir, BiPredicate<Path, BasicFileAttributes> matcher, Consumer<Path> consumer) throws IOException {
BiPredicate<Path, BasicFileAttributes> localMatcher = (path, attr) -> attr.isRegularFile();
localMatcher = matcher != null ? localMatcher.and(matcher) : localMatcher;
Files.find(dir, Integer.MAX_VALUE, localMatcher).forEach(consumer);
}
客户代码:
// define matcher to check if given file name match pattern or not
BiPredicate<Path, BasicFileAttributes> matcher = (path, attr) -> {
String fileName = path.getFileName().toString();
int dot = fileName.lastIndexOf('.');
String ext = dot >= 0 ? fileName.substring(dot + 1) : null;
String name = dot >= 0 ? fileName.substring(0, dot) : fileName;
// check 'name' and 'ext' match the required pattern
return true;
};
// define consumer to accept file path and read it line by line
Consumer<Path> consumer = path -> {
try {
String content = Files.lines(path, StandardCharsets.UTF_8).collect(Collectors.joining(System.lineSeparator()));
System.out.println("file name: " + path);
System.out.println(content);
} catch(IOException e) {
e.printStackTrace();
}
};
readFiles(Paths.get("H://one"), matcher, consumer);