Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent file from being overridden when reading and processing it with Java?

I'd need to read and process somewhat large file with Java and I'd like to know, if there is some sensible way to protect the file that it wouldn't be overwritten by other processes while I'm reading & processing it?

That is, some way to make it read-only, keep it "open" or something...

This would be done in Windows environment.

br, Touko

like image 436
Touko Avatar asked Dec 30 '22 17:12

Touko


1 Answers

you want a FileLock:

FileChannel channel = new RandomAccessFile("C:\\foo", "rw").getChannel();

// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
FileLock lock = channel.tryLock();

// ...  

// release it
lock.release();

for simplicity's sake I've omitted an enclosng try/finally block but you shouldn't in your production code

like image 91
dfa Avatar answered Feb 09 '23 16:02

dfa