Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file-io

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?

like image 833
Jason S Avatar asked Oct 12 '09 18:10

Jason S


1 Answers

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.

like image 68
Taylor Leese Avatar answered Sep 27 '22 22:09

Taylor Leese