【问题标题】: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();
                }
            });

【讨论】:

    【解决方案2】:

    请尝试

    File file = ResourceUtils.getFile("c:\\records\\today\\data1.txt");        
    

    https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

    【讨论】:

      【解决方案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();
                }
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-05-08
          • 2022-01-23
          • 1970-01-01
          • 1970-01-01
          • 2016-04-05
          • 2015-01-25
          • 2017-11-03
          相关资源
          最近更新 更多