简体   繁体   English

如何读取文件夹和子目录中所有文件的内容

[英]How to read content of all files in the folder and in the sub directories

How to read content of all files in the folder and in the sub directories. 如何读取文件夹和子目录中所有文件的内容。 I wrote the method, which get all paths of all files in the folder and in the sub directories. 我编写了该方法,该方法获取该文件夹和子目录中所有文件的所有路径。 How can I read content of all files by getpath? 如何通过getpath读取所有文件的内容?

 public static void pathFiles(File folder) {
            File[] folderEntries = folder.listFiles();
            for (File entry : folderEntries) {
                if (entry.isDirectory()) {
                    processFilesFromFolder(entry);
                    continue;
                }
                System.out.println(entry.getPath());
            }
        }

I think to use the getTextFromFile() , but it get String. 我想使用getTextFromFile() ,但是它得到String。

public static String getTextFromFile(String fileName) throws IOException {
        return new String(Files.readAllBytes(Paths.get(fileName)));

For every file which you found use: 对于找到的每个文件,请使用:

Files.lines(entry.getPath()).forEach(System.out::println);

where entry.getPath() is path to file. 其中entry.getPath()是文件的路径。

Take a look: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path- 看看: https : //docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-

You can use SimpleFileVisitor and Files.lines 您可以使用SimpleFileVisitorFiles.lines

  static class ClassPrinter extends SimpleFileVisitor<Path>{
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.lines(file).forEach(System.out::println);
            return super.visitFile(file, attrs);
        }
    }

This will recursively scan a directory, and on each file, it will print it's content. 这将递归扫描目录,并在每个文件上打印其内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM