java如何迁移文件
使用 Files.copy() 方法迁移文件
Java NIO 包中的 Files.copy() 方法提供了一种简单高效的文件迁移方式。该方法支持覆盖选项和保留文件属性。
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
使用传统IO流迁移大文件
对于大文件迁移,使用缓冲流可以提高性能。这种方法通过分块读写来减少内存占用。
try (InputStream in = new BufferedInputStream(new FileInputStream("source.txt"));
OutputStream out = new BufferedOutputStream(new FileOutputStream("target.txt"))) {
byte[] buffer = new byte[8192];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
}
使用 Files.move() 方法移动文件
如果需要移动而非复制文件,可以使用 Files.move() 方法。这个方法实际上是执行重命名操作,效率更高。
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
处理文件迁移异常
文件操作可能抛出多种异常,需要妥善处理。常见的异常包括文件不存在、权限不足和磁盘空间不足等情况。
try {
Files.copy(source, target);
} catch (NoSuchFileException e) {
System.err.println("源文件不存在");
} catch (AccessDeniedException e) {
System.err.println("没有操作权限");
} catch (IOException e) {
System.err.println("IO错误: " + e.getMessage());
}
迁移整个目录
迁移整个目录需要递归处理所有子目录和文件。可以使用 Files.walk() 方法遍历目录树。

Path sourceDir = Paths.get("sourceDir");
Path targetDir = Paths.get("targetDir");
Files.walk(sourceDir).forEach(source -> {
Path target = targetDir.resolve(sourceDir.relativize(source));
try {
Files.copy(source, target);
} catch (IOException e) {
System.err.println("复制失败: " + source);
}
});






