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

北战南征 提交于 2019-11-30 18:18:57

问题


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


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/1271948/how-to-prevent-file-from-being-overridden-when-reading-and-processing-it-with-ja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!