在Linux上(我相信Solaris和其他UNIX操作系统),如果Java的File.renameTo()方法存在,它将覆盖目标文件,但在Windows下不是这种情况。
为了跨平台,我想你必须在resource.txt上使用文件锁定,然后覆盖数据。
该文件锁的行为是 平台相关。在某些平台上, 文件锁定为通知,这意味着 ,除非应用程序检查文件锁定 ,否则不会阻止 访问该文件。在其他 平台上,文件锁定是强制性的, 这意味着文件锁定会阻止 任何应用程序访问 文件。
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
// Release the lock
lock.release();
// Close the file
channel.close();
} catch (Exception e) {
}
的Linux,默认情况下,采用自愿锁定,而Windows强制执行它。也许你可以检测到操作系统,并在Windows下使用一些锁定代码在UNIX下使用renameTo()?
还有一种方法可以在Linux下针对特定文件启用强制锁定,但它有点模糊。您必须正确设置模式位。
Linux的,下面的System V(请参阅系统 V接口定义(SVID)版本 3),让SGID位的文件 没有组执行权限标志 文件进行强制性锁定
自我提醒,8年后:我不记得的背景下,但如果* *问题,需要跨平台的原子性,也许*解决方案*不应该涉及一个文件? – 2018-02-12 09:32:22