使用 FileLock 将行附加到文件

Appending line to file with FileLock

这是我见过的向文件追加行的最清晰的方式。 (如果文件不存在则创建文件)

String message = "bla";
Files.write(
    Paths.get(".queue"),
    message.getBytes(),
    StandardOpenOption.CREATE,
    StandardOpenOption.APPEND);

但是,我需要在它周围添加 (OS) 锁定。我浏览了 FileLock 的示例,但在 Oracle Java 教程中找不到任何规范示例,而且 API 对我来说非常难以理解。

不围绕此代码。您必须通过 FileChannel 打开文件,获取锁,进行写入,然后关闭文件。或者释放锁定并保持文件打开,如果您愿意,那么您只需在下次锁定。请注意,文件锁只能保护您免受其他文件锁的侵害,而不能防止您发布的代码。

您可以通过检索流媒体频道并锁定文件来锁定文件。

行中的内容:

new FileOutputStream(".queue").getChannel().lock();

您也可以使用 tryLock,具体取决于您想要的平滑程度。

现在开始编写和锁定,您的代码将如下所示:

try(final FileOutputStream fos = new FileOutputStream(".queue", true);
    final FileChannel chan = fos.getChannel()){
    chan.lock();
    chan.write(ByteBuffer.wrap(message.getBytes()));
}

请注意,在本示例中,我使用 Files.newOutputStream 添加您的打开选项。

您可以对 FileChannel 应用锁定。

 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();

        /*
           use channel.lock OR channel.tryLock();
        */

        // 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 - if it is not null!
        if( lock != null ) {
            lock.release();
        }

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

有关更多信息,您可以阅读本教程:

  1. How can I lock a file using java (if possible)
  2. Java FileLock for Reading and Writing