Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock a file and delete it without first releasing the lock

Tags:

java

file-io

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.

like image 361
Scrubbie Avatar asked Dec 03 '10 22:12

Scrubbie


1 Answers

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.

like image 154
Mark Byers Avatar answered Oct 01 '22 18:10

Mark Byers