0

我编写了一个访问文件的 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)

据我了解FileLock 如何工作?, 实际获得的锁

f.tryLock()

禁止我访问它,因为另一个进程(显然是这个)具有排他锁。

现在这让我觉得很矛盾——当获得锁的实际行为阻碍我这样做时,我如何获得一个独占锁以使我能够写入文件而不会有其他进程弄乱它的危险?

因此,为什么它可以在 Mac OS 上运行而不是在 Windows 上运行?我从 JavaDocs 中知道 FileLock 类存在操作系统特定的差异和困难,但肯定不是针对其设计的功能。既然不能这样,我做错了,这就是我请求你帮助的地方。

谢谢,米

4

1 回答 1

0

There is no file locking on UNIX.: http://www.coderanch.com/t/551144/java/java/File-lock-doesn-prevent-threads. In fact, on UNIX, you can delete a file from under a process and it may not even notice...
So you need to use a lock file that you can check exists.
Paradoxically your code is working on Windows but not on UNIX (i.e. Mac OS), the exception should be the expected result of trying to write to a file that is locked by another process.

于 2013-02-20T10:49:40.370 回答