← 中文资源

简体中文版本

Files 拷贝移动与原子替换

用 NIO Files 的 REPLACE_EXISTING 与 ATOMIC_MOVE 选项拷贝、晋升文件:中断也不会留下半写状态,并保留降级路径。

阅读英文原文

实现说明

底层就是类 StagePromotion。

常见问题

「Files 拷贝移动与原子替换」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

核心语句

Files.move(release, promoted, StandardCopyOption.REPLACE_EXISTING);
Files.copy(staging, release, StandardCopyOption.REPLACE_EXISTING);
Files.writeString(staging, "build 2026-11-09\nchecksum ok\n");

代码示例

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class StagePromotion {

    public static void main(String[] args) throws IOException {
        Path staging = Files.createTempFile("deploy-", ".tmp");
        Path release = staging.resolveSibling("release.txt");

        Files.writeString(staging, "build 2026-11-09\nchecksum ok\n");

        // 拷贝:显式声明覆盖语义
        Files.copy(staging, release, StandardCopyOption.REPLACE_EXISTING);

        // 原子改名:同目录内 promote,绝不出现半写状态
        Path promoted = staging.resolveSibling("release-final.txt");
        try {
            Files.move(release, promoted, StandardCopyOption.ATOMIC_MOVE);
        } catch (IOException fallback) {
            // 个别文件系统不支持原子移动:退回普通 move
            Files.move(release, promoted, StandardCopyOption.REPLACE_EXISTING);
        }

        System.out.println(promoted + " -> " + Files.readAllLines(promoted));
        Files.deleteIfExists(staging);
        Files.deleteIfExists(promoted);
    }
}