可以使用Java NIO(New I/O)包中的Files和Paths类来遍历文件夹并读取文件内容。下面是一个基本的示例代码:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileReadingExample {
public static void main(String[] args) throws IOException {
Path folderPath = Paths.get("C:/myFolder");
Files.walk(folderPath)
.filter(Files::isRegularFile)
.forEach(filePath -> {
try {
String content = Files.readString(filePath, StandardCharsets.UTF_8);
System.out.println(content);
} catch (IOException e) {
System.err.println(e.getMessage());
}
});
}
}
在上面的代码中,我们使用Paths.get(path)来创建一个Path对象,指定要遍历的文件夹。然后,我们使用Files.walk(folderPath)来遍历该文件夹及其所有子文件夹中的文件。使用filter(Files :: isRegularFile)过滤出只是文件的文件路径。最后,我们使用Files.readString(filePath,StandardCharsets.UTF_8)从文件路径中读取内容。遍历过程中,我们打印读取的内容。
注意,在处理大量文件时,建议使用线程池或并行流以提高性能和效率。
希望这个解决方案对你有所帮助!