0

How can i lock a file then clear its contents and write to it? Clearing a file can be as simple as:

FileOutputStream fos = new FileOutputStream(someFileObject);

And acquiring the lock would be by:

FileLock lock = fos.getChannel().lock();

But what i need is to lock the file before i clear it because i don't want any edits to happen before the program gets the lock for the file.

I tried using 2 FileOutputStream objects one that is set to append and is just used for locking and the other one with append set to false for clearing the file like so:

    File log = new File("test.txt");
    try (FileOutputStream forLocking = new FileOutputStream(log, true)) {
        FileChannel fileChannel = forLocking.getChannel();
        FileLock lock = fileChannel.lock();
        try (FileOutputStream fos = new FileOutputStream(log); PrintWriter out = new PrintWriter(fos);) {
            out.println("Test this stuff");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

but apparently only the Channel that has the lock can make any changes to it in the same jvm at least.

Is there anyway i can go about with this without having to delete the file and recreate it?

I appreciate the help.

@Roman Puchkovskiy I know how to lock. and i know how to clear a file. My question is how can i acquire a lock then clear the file in the respective order. The link you sent is not helpful at all thanks for trying though.

Omar Alama
  • 29
  • 6

1 Answers1

0

By reading the doc I found that you can create a RandomAccessFile instance first, then call getChannel on it. Once you get the channel, you can lock it and channel.truncate(0) will clear its content. You can then proceed to write to the file by calling channel.write(byteBuffer).

Here's what I mean:

RandomAccessFile raFile = new RandomAccessFile(filename, 'rw');
FileChannel fc = raFile.getChannel();
fc.lock();
fc.truncate(0);
fc.write(someBuffer);
raFile.close(); // Will release the lock.
maowtm
  • 1,982
  • 1
  • 18
  • 22
  • Thanks, using the FileOutputStream works too. i created a new one with append set to true i then locked the channel and called truncate(0) like you said and that cleared the file. then i used a print writer normally to write stuff. – Omar Alama Jun 24 '17 at 20:15
  • @OmarAlama Please check out the edited answer. I may have made a mistake. – maowtm Jun 24 '17 at 20:16
  • In reply to your edit: actually just creating the stream will simply clear the file. unless you create it using this constructer (someFileObject, true) which will set it to append and not clear. but yeah the truncate(0) is what i needed. thanks – Omar Alama Jun 24 '17 at 20:19