我有文件A和文件B并且想要交换它们。 (In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables)
File fileA, fileB, temp
fileA.renameTo(temp);
try {
fileB.renameTo(fileA);
try {
// process fileA, B
} finally {
fileA.renameTo(fileB);
}
} finally {
temp.renameTo(fileA);
}
如果存在“硬件”交换操作,我会避免使用临时文件和一对重命名。
最佳答案
一般来说,不存在“原子”文件交换操作的概念。即使有,它也会依赖于文件系统。我不相信“常见”文件系统(FAT*、ext*、NTFS 等)支持原子交换操作。
当然,原子操作不能通过Java实现。即使是这样,它也永远无法跨文件系统等工作。
您正在寻找的东西在 Java 中找不到家,仅仅是因为它永远无法保证在 Java 运行的各种受支持的平台上。
将 temp 与 some file locking 一起使用是获得相对可靠的交换操作的唯一方法。
关于java - 交换磁盘上的两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18858826/