gpt4 book ai didi

recursion - Java 8 : Copy directory recursively?

转载 作者:行者123 更新时间:2023-12-03 01:18:32 25 4
gpt4 key购买 nike

我发现 Java 8 已经显着清理了将文件内容读取到字符串中的过程:

String contents = new String(Files.readAllBytes(Paths.get(new URI(someUrl))));

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

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 有什么改进吗?

最佳答案

这样代码看起来简单了一些

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

关于recursion - Java 8 : Copy directory recursively?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29076439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com