在Java中,当文件被其他线程锁定时,是否有读取文件的方法? [英] In Java, Is there a way to read a file when that file is locked by other thread?
问题描述
文件文件=新的文件(文件名);
channel = new RandomAccessFile(file,rw)。getChannel();
lock = channel.tryLock();
现在我有第二个线程要访问同一个文件 - 只是读,不能编辑。我怎么做?现在第二个线程会抛出一个io异常,并通知我这个文件被锁定。
这是可行的吗?有什么建议么?谢谢
您可以尝试使用tryLock的三个参数版本来请求共享锁。
以下是相应的javadoc:
http://download.oracle.com/javase/1.4.2/docs/api/java/ nio / channels / FileChannel.html#tryLock%28long,%20long,%20boolean%29
基本上不用做
lock = channel.tryLock()
你会做
lock = channel.trylock(0,Long.MAX_VALUE,true)
另外,你应该小心java中的文件锁定。虽然您可以保证锁定在JVM中按照预期运行,但您不一定能确定它们将在多个进程中按预期运行。
So i used the following to create a lock on a file so that I can edit it exclusively:
File file = new File(filename);
channel = new RandomAccessFile(file, "rw").getChannel();
lock = channel.tryLock();
Now I have a 2nd thread want to access the same file - just to read, not edit. How do i do that? Right now the 2nd thread will throw an io exception and inform me the file is locked.
Is this doable? Any suggestions? Thanks
You could try asking for a shared lock using the three argument version of tryLock.
Here is the appropriate javadoc: http://download.oracle.com/javase/1.4.2/docs/api/java/nio/channels/FileChannel.html#tryLock%28long,%20long,%20boolean%29
Basically instead of doing
lock=channel.tryLock()
you would do lock = channel.trylock(0, Long.MAX_VALUE, true)
As an aside, you should be careful with file locking in java. While you can guarantee the locks behave as expected within the JVM you can't necessarily be sure that they will behave as expected accross multiple processes.
这篇关于在Java中,当文件被其他线程锁定时,是否有读取文件的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!