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?
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.
File.createNewFile()
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
EDIT
Jason, as for your concern, if you keep reading the link we sent you there is a NOTE about that.
Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.
I think you should really read that part too:
Java 7 version with Files#createFile:
Path out;
try {
out = Files.createFile(Paths.get("my-file.txt"));
} catch (FileAlreadyExistsException faee) {
out = Paths.get("my-file.txt");
}
Why can't you test using File#exists?
//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;
}