如何在Java中自动重命名文件,即使dest文件已经存在? [英] How to atomically rename a file in Java, even if the dest file already exists?

查看:760
本文介绍了如何在Java中自动重命名文件,即使dest文件已经存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组机器,每台都运行一个Java应用程序。

I have a cluster of machines, each running a Java app.

这些Java应用程序需要访问一个唯一的 resource.txt 文件很简洁。

These Java apps need to access a unique resource.txt file concurently.

我需要将 temp.txt 文件原子地重命名为<$ c Java中的$ c> resource.txt ,即使 resource.txt 已经存在。

I need to atomically rename a temp.txt file to resource.txt in Java, even if resource.txt already exist.

删除 resource.txt 并重命名 temp.txt 不起作用,因为它不是原子的(它创建了一个 resource.txt 不存在的小时间段。

Deleting resource.txt and renaming temp.txt doesn't work, as it's not atomic (it creates a small timeframe where resource.txt doesn't exist).

它应该是跨平台的......

And it should be cross-platform...

谢谢!

推荐答案

对于Java 1.7+,请使用 java.nio.file.Files.move(Path source,Path target,CopyOption ... options) with CopyOptionsREPLACE_EXISTING和ATOMIC_MOVE。

For Java 1.7+, use java.nio.file.Files.move(Path source, Path target, CopyOption... options) with CopyOptions "REPLACE_EXISTING" and "ATOMIC_MOVE".

有关详细信息,请参阅API文档。

例如:

Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);

这篇关于如何在Java中自动重命名文件,即使dest文件已经存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆