Java 8: Copy directory recursively?

后端 未结 6 1655
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 19:47

I see that Java 8 has significantly cleaned up reading the contents of a file into a String:

String contents = new String(Files.readAllBytes(Paths.get(new URI(so         


        
6条回答
  •  遥遥无期
    2021-02-03 20:08

    Using Files.walkFileTree:

    • you don't need to worry about closing Streams.
      (some other answers here forget that while using Files.walk)
    • handles IOException elegantly.
      (Some other answers here would become more difficult when adding proper exception handling instead of a simple printStackTrace)
        public void copyFolder(Path source, Path target, CopyOption... options)
                throws IOException {
            Files.walkFileTree(source, new SimpleFileVisitor() {
    
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    createDirectories(target.resolve(source.relativize(dir)));
                    return FileVisitResult.CONTINUE;
                }
    
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                        throws IOException {
                    copy(file, target.resolve(source.relativize(file)), options);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    

    What this does is

    • walk recursively over all files in the directory.
    • When a directory is encountered (preVisitDirectory):
      create the corresponding one in the target directory.
    • When a regular file is encountered (visitFile):
      copy it.

    options can be used to tailor the copy to your needs. For example to overwrite existing files in the target directory, use copyFolder(source, target, StandardCopyOption.REPLACE_EXISTING);

提交回复
热议问题