我看到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有哪些改进?
Files.readAllBytes(Paths.get(new URI(someUrl))
自Java 7起可用。 - assyliasjava.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)
完成,该方法自1.7版本起可用。 - bowmore