Skip to content
Advertisement

The optimal way to lock and write to a file in Scala on Linux

I’m having a hard time finding the correct way to do any advanced file-system operations on Linux using Scala.

The one which I really can’t figure out if best described by the following pseudo-code:

JavaScript

Basically open a file in append mode (create it if it’s non existent), get an exclusive lock to it and write to it (with the implicit unlock and close afterwards).

Is there an easy, clean and efficient way of doing this if I know my program will be ran on linux only ? (preferably without glancing offer the exceptions that should be handled).

Edit:

The answer I got is, as far as I’ve seen and tested is correct. However it’s quite verbose, so I’m marking it as ok but I’m leaving this snippet of code here, which is the one I ended up using (Not sure if it’s correct, but as far as I see it does everything that I need):

JavaScript

Advertisement

Answer

You can use FileChannel.lock and FileLock to get what you wanted:

JavaScript
Advertisement