Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从路径读取文件夹中的文件_Java_Spring_Eclipse_Spring Boot_Maven - Fatal编程技术网

Java 从路径读取文件夹中的文件

Java 从路径读取文件夹中的文件,java,spring,eclipse,spring-boot,maven,Java,Spring,Eclipse,Spring Boot,Maven,我需要读取文件夹中的所有文件。这是我的路径c:/records/today/路径中有两个文件data1.txt和data2.txt。得到文件后,我需要读取并显示它。 我已经处理了第一个文件,我只是不知道如何同时处理这两个文件 File file = ResourceUtils.getFile("c:/records/today/data1.txt"); String content = new String(Files.readAllBytes(file.to

我需要读取文件夹中的所有文件。这是我的路径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");        

请参见

要读取特定文件夹中的所有文件,您可以按如下方式执行:

File dir = new File("c:/records/today");      
for (File singleFile: dir.listFiles()) {
    // do file operation on singleFile
}  

您可以稍微更改代码,而不是使用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();
        }
    });

此外,您还可以使用它来检查子路径isFile或directory

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();
                }
            });

那么是什么阻止你对第二个文件做同样的事情呢?