Search code examples
javaiolockingnio

Appending line to file with FileLock


This is the clearest means I've seen of appending lines to a file. (and creating the file if it doesn't already exist)

String message = "bla";
Files.write(
    Paths.get(".queue"),
    message.getBytes(),
    StandardOpenOption.CREATE,
    StandardOpenOption.APPEND);

However, I need to add (OS) locking around it. I've browsed through examples of FileLock, but can't find any canonical examples in the Oracle Java tutorials, and the APIs are pretty impenetrable to me.


Solution

  • You can lock a file retrieving it stream channel and locking it.

    Something amongs the line of :

    new FileOutputStream(".queue").getChannel().lock();
    

    You can also use tryLock depending on how smooth you want to be.

    Now to write and lock, your code would looks like this :

    try(final FileOutputStream fos = new FileOutputStream(".queue", true);
        final FileChannel chan = fos.getChannel()){
        chan.lock();
        chan.write(ByteBuffer.wrap(message.getBytes()));
    }
    

    Notice that in this example, I used Files.newOutputStream to add your opening options.