这是我所见过的在文件中附加行的最清晰的方法。(如果该文件不存在,则创建该文件)
String message = "bla";
Files.write(
Paths.get(".queue"),
message.getBytes(),
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);但是,我需要在它周围添加(OS)锁定。我已经浏览过FileLock的示例,但是在Oracle教程中找不到任何规范的示例,API对我来说是很难理解的。
发布于 2016-07-29 01:01:19
您可以锁定一个文件,检索它的流通道并锁定它。
某物中的某物:
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添加了您的开始选项。
发布于 2016-07-29 01:01:18
而不是绕过这个密码。您必须通过FileChannel打开文件,获取锁,进行写入,关闭文件。或者释放锁,并保持文件打开,如果你愿意,所以你只需要锁定下一次。注意,文件锁只保护您不受其他文件锁的影响,而不是针对您发布的代码。
发布于 2016-07-29 01:09:16
您可以将锁应用于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) {
}要了解更多信息,您可以阅读本教程:
https://stackoverflow.com/questions/38648869
复制相似问题