I'm trying to implement the following operation in Java and am not sure how:
/*
* 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
}
}
Is there a function that exists already that I can use for atomicCreateFile()
?
edit: Uh oh, I'm not sure that File.createNewFile() is sufficient for my needs. What if I call f.createNewFile()
and then between the time that it returns and I open the file for writing, someone else has deleted the file? Is there a way I can both create the file and open it for writing + lock it, all in one fell swoop? Do I need to worry about this?