从路径读取文件夹内的文件
Read files inside a folder from a path
我需要读取文件夹中的所有文件。这是我的路径 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);
请尝试
File file = ResourceUtils.getFile("c:\records\today\data1.txt");
见https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
要读取特定文件夹中的所有文件,您可以像下面这样操作:
File dir = new File("c:/records/today");
for (File singleFile: dir.listFiles()) {
// do file operation on singleFile
}
您可以稍微更改代码,而不是使用 Resources.getFile 使用 Files.walk 到 return 文件流并遍历它们。
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();
}
});
此外,您可以使用它来检查子路径是文件还是目录
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();
}
});
我需要读取文件夹中的所有文件。这是我的路径 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);
请尝试
File file = ResourceUtils.getFile("c:\records\today\data1.txt");
见https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
要读取特定文件夹中的所有文件,您可以像下面这样操作:
File dir = new File("c:/records/today");
for (File singleFile: dir.listFiles()) {
// do file operation on singleFile
}
您可以稍微更改代码,而不是使用 Resources.getFile 使用 Files.walk 到 return 文件流并遍历它们。
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();
}
});
此外,您可以使用它来检查子路径是文件还是目录
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();
}
});