4

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

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hi still, is there some way to prevent the file being edited? If I acquire exlusive lock under Windows and open it with text editor (Scite for example), it is opened with empty content but if I write something and save, the file ends up emptied in the end? In contrast, if I try to open it with Eclipse, it tells me that the file can't be opened because it's locked by another process... This probably ends up to Windows, but somebody got some ideas?
0

Working mostly fine, got some issues : as the locking doesn't seem to be totally absolute.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.