Dana Dabbagh Dana Dabbagh - 1 year ago 64
Java Question

How do I write/read to a file that I've locked?

I'm writing a program that is threaded and potentially will run across multiple JVMs. I am having issues with writing and reading to a file once I've locked it (to prevent other processes/threads from accessing it). I was originally using a

but nothing was being written to the file.

Now I'm trying an
and for some reason new writes to the file won't append - so only the last entry will appear. What am I doing wrong? What's the best way to read/write to a file once you've locked it?

Note: if I delete all the locks and use
combined with
I don't have these issues so I think my locking mechanism is wrong

try {
// Get a file channel for the file
File file = new File ( path );
RandomAccessFile stream = new RandomAccessFile(file, "rw");
FileChannel channel = stream.getChannel();

// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();

OutputStream os = Channels.newOutputStream(channel);

try (PrintWriter pw = new PrintWriter(os,true)){
System.out.println("Writing " + message);
// Release the lock - if it is not null!
if( lock != null ) {
// Close the file

} catch (Exception e) {

Answer Source

A simpler solution would be to use a FileOutputStream

FileOutputStream os = new FileOutputStream(path, true);
FileChannel channel = os.getChannel();

When you use

new FileWriter(os, true)

the true mean "append mode" however when you use

new PrintWriter(os,true)

the true means; "flush on newline" i.e. it will always overwrite

When you need to do is to only write from the end of the file. I suggest you use


before you attempt to append.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download