【发布时间】:2013-02-20 10:45:18
【问题描述】:
我编写了一个访问文件的 java 应用程序,而其他 VM 中的其他进程尝试执行相同操作。因此我使用 FileLock 类:
FileOutputStream fos = new FileOutputStream(filePath,append);
FileChannel f = fos.getChannel();
FileLock lock;
while ((lock = f.tryLock()) == null){
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
}
}
OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(filePath,append));
out.write(textToWrite);
out.close();
lock.release();
在 Mac OSX 上一切正常,但是当我在 Windows 7 上运行代码时,它会在该行抛出 IOException
out.close();
,尝试刷新时。
java.io.IOException: The process cannot access the file because another process has locked a portion of the file
at java.io.FileOutputStream.writeBytes(Native Method)
据How does FileLock work?了解,实际获取锁的方式是
f.tryLock()
禁止我访问它,因为另一个进程(显然是这个)具有排他锁。
现在这让我觉得很矛盾——当获得锁的实际行为阻碍我写文件时,我如何获得一个独占锁以使我能够写入文件而不会有其他进程弄乱它的危险这样做?
那么为什么它可以在 Mac OS 上运行而不是在 Windows 上呢?我从 JavaDocs 中知道 FileLock 类存在操作系统特定的差异和困难,但肯定不是针对其设计的功能。 既然不能这样,我做错了,我在这里寻求你的帮助。
谢谢, M
【问题讨论】:
标签: java windows ioexception filelock