【问题标题】:Read files inside a folder from a path从路径读取文件夹内的文件
【发布时间】:2021-06-25 10:30:08
【问题描述】:
我需要读取文件夹中的所有文件。这是我的路径 c:/records/today/,路径内部有两个文件 data1.txt 和 data2.txt。获取文件后,我需要阅读并显示它。
我已经用第一个文件做了,我只是不知道如何做。
File file = ResourceUtils.getFile("c:/records/today/data1.txt");
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
【问题讨论】:
标签:
java
spring
eclipse
spring-boot
maven
【解决方案1】:
此外,您可以使用它来检查子路径 isFile 或目录
Arrays.stream(ResourceUtils.getFile("c:/records/today/data1.txt").listFiles())
.filter(File::isFile)
.forEach(file -> {
try {
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
});
【解决方案3】:
要读取特定文件夹中的所有文件,您可以执行以下操作:
File dir = new File("c:/records/today");
for (File singleFile: dir.listFiles()) {
// do file operation on singleFile
}
【解决方案4】:
您可以稍微更改代码,而不是使用 Resources.getFile 使用 Files.walk 返回文件流并对其进行迭代。
Files.walk(Paths.get("c:\\records\\today\)).forEach(x->{
try {
if (!Files.isDirectory(x))
System.out.println(Files.readAllLines(x));
//Add internal folder handling if needed with else clause
} catch (IOException e) {
//Add some exception handling as required
e.printStackTrace();
}
});