Lock a file and delete it without first releasing the lock
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 t开发者_JS百科he 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.
Can you move the file to an alternate location (where other potential processes can't find it) and then do your work on it there? If not, what about clearing the data in the file prior to releasing the lock?
精彩评论