Jason S Jason S - 11 days ago 6
Java Question

how to create a file in Java only if one doesn't already exist?

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?

Answer

File.createNewFile() only creates a file if one doesn't already exist.

EDIT: Based on your new description of wanting to lock the file after it's created you can use the java.nio.channels.FileLock object to lock the file. There isn't a one line create and lock though like you are hoping. Also, see this SO question.