I want to read from a file and then delete it, all the while preventing other processes from accessing it. How can this be accomplished?
FileLock won't work because you have to release the lock and close the channel before you can call File.delete(). My concern is that after releasing the lock another process might lock it and start reading before the file is deleted.
I am using Java 5 and upgrading to 6 is not an option at this time.
I don't know if that's possible but a simple solution is to use the operating system users and permissions to make sure that only your process can read the file.
Another approach is to rename the file to a randomly generated string then afterward lock, read, unlock then delete the renamed file. In theory another program could guess the filename and read the file just after it's unlocked but before it is deleted. But in practice you'll probably be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With