锁定档案

时间:2011-01-03 09:39:10

标签: java

我使用我的应用程序访问保存在服务器上的一些文件。多个用户可以登录到应用程序,我想对一个用户打开的文件进行一些显式锁定,并希望在用户注销或停止使用该文件时释放锁定。

任何帮助怎么做?

提前致谢

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

try {
    // Get a file channel for the file
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

    // Use the file channel to create a lock on the file.
    // This method blocks until it can retrieve the lock.
    FileLock lock = channel.lock();

    // Try acquiring the lock without blocking. This method returns
    // null or throws an exception if the file is already locked.
    try {
        lock = channel.tryLock();
    } catch (OverlappingFileLockException e) {
        // File is already locked in this thread or virtual machine
    }

    // Release the lock
    lock.release();

    // Close the file
    channel.close();
} catch (Exception e) {
}

希望这会对你有所帮助

答案 1 :(得分:0)

您可以尝试使用FileLock。它们可能很难做到,但它可能是您唯一的选择。

答案 2 :(得分:0)

您使用的是数据库吗?为什么没有一个表列出用户锁定的文件?然后,您可以通过插入/删除行来获取和释放锁。

不要忘记管理界面来释放错误保存的锁。还要考虑实现一种超时(即锁定在XX小时后不再有效)