首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java 8:递归复制目录?

Java 8:递归复制目录?
EN

Stack Overflow用户
提问于 2015-03-16 20:08:28
回答 7查看 30.7K关注 0票数 41

我看到Java 8已经将文件内容读入字符串进行了显着的清理:

代码语言:javascript
复制
String contents = new String(Files.readAllBytes(Paths.get(new URI(someUrl))));

我想知道是否有类似的东西(更干净/更少的代码/更简洁)来递归复制目录。在Java 7领域,它仍然是这样的:

代码语言:javascript
复制
public void copyFolder(File src, File dest) throws IOException{
    if(src.isDirectory()){
        if(!dest.exists()){
            dest.mkdir();
        }

        String files[] = src.list();

        for (String file : files) {
            File srcFile = new File(src, file);
            File destFile = new File(dest, file);

            copyFolder(srcFile,destFile);
        }

    } else {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dest); 

        byte[] buffer = new byte[1024];

        int length;
        while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
        }

        in.close();
        out.close();
    }
}

Java 8中有什么改进吗?

EN

回答 7

Stack Overflow用户

发布于 2018-05-19 03:27:07

这样,代码看起来就简单了一点。

代码语言:javascript
复制
import static java.nio.file.StandardCopyOption.*;

public  void copyFolder(Path src, Path dest) throws IOException {
    try (Stream<Path> stream = Files.walk(src)) {
        stream.forEach(source -> copy(source, dest.resolve(src.relativize(source))));
    }
}

private void copy(Path source, Path dest) {
    try {
        Files.copy(source, dest, REPLACE_EXISTING);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
票数 28
EN

Stack Overflow用户

发布于 2020-03-11 00:07:15

使用Files.walkFileTree

  • 你不需要担心关闭流。

(这里的其他一些答案在优雅地使用Files.walk)

  • handles IOException时忘记了这一点。

(当添加适当的异常处理而不是简单的printStackTrace)时,这里的一些其他答案会变得更加困难

代码语言:javascript
复制
    public void copyFolder(Path source, Path target, CopyOption... options)
            throws IOException {
        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException {
                Files.createDirectories(target.resolve(source.relativize(dir)));
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                Files.copy(file, target.resolve(source.relativize(file)), options);
                return FileVisitResult.CONTINUE;
            }
        });
    }

这样做的目的是

遇到目录(preVisitDirectory)时,

  • 会递归遍历directory.
  • When中的所有文件:

在遇到常规文件的目标directory.

  • When中创建相应的文件(visitFile):

复制。

options可用于根据您的需要定制副本。例如,要覆盖目标目录中的现有文件,请使用copyFolder(source, target, StandardCopyOption.REPLACE_EXISTING);

票数 18
EN

Stack Overflow用户

发布于 2015-12-14 01:35:58

下面的代码怎么样?

代码语言:javascript
复制
public void copyFolder(File src, File dest) throws IOException {
        try (Stream<Path> stream = Files.walk(src.toPath())) {
            stream.forEachOrdered(sourcePath -> {

                try {
                    Files.copy(
                            /*Source Path*/
                            sourcePath,
                            /*Destination Path */
                            src.toPath().resolve(dest.toPath().relativize(sourcePath)));
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            });
        }
    }
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29076439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档