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.