使用Path和Files工具类编写一个FilesCopy类,该类包含一个静态方法filesCopy(Path from,Path to),实现把from目录中的文件(文件包括:文件、子文件夹及子文件夹中的文件)复制到to目录中
直接上代码:
package io_Package;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class FilesCopy {
public static void filesCopy(Path from,Path to) throws IOException{
long startTime = System.currentTimeMillis();
final Path destPath = Paths.get(to.toString(), from.toFile().getName());
//检查源文件是否存在
if(Files.notExists(from)){
System.out.println("源文件不存在");
System.exit(1);
}
//如果目标文件不存在则创建
if(Files.notExists(destPath)){
Files.createDirectories(destPath);
}
Files.walkFileTree(from, new SimpleFileVisitor<Path>() {
@Override
// 文件处理,将文件夹也一并处理,简洁些
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Path dest = destPath.resolve(from.relativize(file));
// 如果说父路径不存在,则创建
if (Files.notExists(dest.getParent())) {
Files.createDirectories(dest.getParent());
}
//copy方法只能复制不存在的路径
Files.copy(file, dest);
/*复制并覆盖的方法
Files.copy(file, dest, StandardCopyOption.REPLACE_EXISTING);
*/
return FileVisitResult.CONTINUE;
}
});
long endTime = System.currentTimeMillis();
System.out.println("复制成功!耗时:" + (endTime - startTime) + "ms");
}
public static void main(String[] args) {
Path from = Paths.get("D:\\hello");
Path to = Paths.get("D:\\copyHello");
try {
filesCopy(from,to);
} catch (IOException e) {
e.printStackTrace();
}
}
}
注:文章有参考其他博客,如有侵犯,请联系我删除。