How to create a file in Java?

I'm trying to implement the following operations in Java. I don't know how to:

/*
 * 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 already exists for atomiccreatefile()?

Editor: Well, I don't know file Is createnewfile () sufficient for my needs What if I call f.createnewfile() and write between the time it returns and the time I open the file, and someone else deletes the file? Is there any way I can create a file and open it to write locks, every move? Do I need to worry?

Solution

File. Createnewfile() creates a file only if there is no file

Edit: Based on the new description that you want to lock the file after it is created, you can use Java nio. channels. Filelock object to lock the file No line is created and locked, as you want See also so question

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>