我看到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中有什么改进吗?
发布于 2018-05-19 03:27:07
这样,代码看起来就简单了一点。
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);
}
}发布于 2020-03-11 00:07:15
使用Files.walkFileTree
(这里的其他一些答案在优雅地使用Files.walk)
IOException时忘记了这一点。(当添加适当的异常处理而不是简单的printStackTrace)时,这里的一些其他答案会变得更加困难
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.
visitFile):复制。
options可用于根据您的需要定制副本。例如,要覆盖目标目录中的现有文件,请使用copyFolder(source, target, StandardCopyOption.REPLACE_EXISTING);
发布于 2015-12-14 01:35:58
下面的代码怎么样?
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);
}
});
}
}https://stackoverflow.com/questions/29076439
复制相似问题