Java 8:递归复制目录? [英] Java 8: Copy directory recursively?
本文介绍了Java 8:递归复制目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到Java 8已经大大清理了将文件内容读入字符串:
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(someUrl))));
我想知道是否有类似的东西(更干净/更少的代码/更简洁)递归复制目录。在Java 7中,它仍然是这样的:
I am wondering if there is something similar (cleaner/less code/more concise) for copying directories recursively. In Java 7 land, it's still something like:
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中的任何改进?
Any improvements here in Java 8?
推荐答案
以下代码怎么样
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 (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
}
这篇关于Java 8:递归复制目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文