java - 无法在 Java 中读取或写入锁定的文件

标签 java concurrency filelock

我已经使用 Java 中的 FileLock 锁定了一个文件,但现在我无法读取或写入该文件。我该怎么办?

最佳答案

虽然这个问题可能有很多潜在的解决方案,但我发现以下方法效果很好:

// Gets a readable and writable channel to your file.
FileChannel channel = new RandomAccessFile(yourFile, "rw").getChannel();

// Allows you to read from the file.
InputStream in = Channels.getInputStream(channel);

// Allows you to write to the file.
OutputStream out = Channels.getOutputStream(channel);

// Lock the file here as you see fit to prevent concurrency issues.
// As a concrete example, you could attempt to lock the file using "channel.tryLock()"
...

当我遇到这个问题时,我发现它非常令人沮丧,所以我想我应该与其他可能需要它的人分享我的解决方案。

关于java - 无法在 Java 中读取或写入锁定的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11977901/

相关文章:

java - 如何处理Map <String,List>中对List的同步访问?

python - 为什么 Python filelock 库在 Windows 而不是 UNIX 上删除锁定文件?

java - 未关闭httpclient有影响吗?

java - Selenium 网络驱动程序 : Suppress IE log info prints on the console

java - JFOREX SDK - 如何向 www 服务器 ssl 连接发送 HTTPS GET 请求

java - 如何使用selenium(JAVA)按列名称和行索引自动单击表格单元格中的链接

php - innodb中的并发

c# - 在c#中,如何在多线程环境下迭代IEnumerable

c# - FileStream 保存文件然后立即在 .NET 中解锁?

python - Django 发送邮件 "lock already in place. quitting."