我正在尝试用Java实现以下操作,我不确定如何:
/*
* write data (Data is defined in my package)
* to a file only if it does not exist, return success
*/
boolean writeData(File f, Data d)
{
FileOutputStream fos = null;
try
{
fos = atomicCreateFile(f);
if (fos != null)
{
/* write data here */
return true;
}
else
{
return false;
}
}
finally
{
fos.close(); // needs to be wrapped in an exception block
}
}
是否存在我可用于atomicCreateFile()
的功能?
编辑哦,我不确定File.createNewFile()是否足以满足我的需求。如果我调用f.createNewFile()
然后在它返回的时间和我打开文件进行写入之间,其他人已经删除了该文件,该怎么办?有没有办法我可以创建文件并打开它来写入+锁定它,一举一动?我需要担心吗?
答案 0 :(得分:18)
File.createNewFile()
仅在尚未存在的情况下创建文件。
编辑:根据您在创建文件后想要锁定文件的新描述,您可以使用java.nio.channels.FileLock
对象来锁定文件。就像你希望的那样,没有一条线创造和锁定。另请参阅此SO question。
答案 1 :(得分:7)
原子 创建一个由此抽象路径名命名的新空文件,当且仅当具有此名称尚不存在。检查文件是否存在以及文件的创建(如果不存在)是针对可能影响文件的所有其他文件系统活动的原子操作。
修改强>
杰森,至于你的担心,如果你继续阅读我们发给你的链接,那就有一个注意事项。注意: 此方法不应用于文件锁定,因为无法使生成的协议可靠地工作。应该使用FileLock工具。
我认为你也应该真正阅读这一部分:
答案 2 :(得分:2)
带有Files#createFile的Java 7版本:
Path out;
try {
out = Files.createFile(Paths.get("my-file.txt"));
} catch (FileAlreadyExistsException faee) {
out = Paths.get("my-file.txt");
}
答案 3 :(得分:-1)
为什么不能使用File#exists进行测试?
答案 4 :(得分:-2)
//myFile should only be created using this method to ensure thread safety
public synchronized File getMyFile(){
File file = new File("path/to/myfile.ext");
if(!file.exists()){
file.getParentFile().mkdirs();
file.createNewFile();
}
return file;
}