无法从Java中的锁定文件读取或写入

时间:2012-08-15 21:52:06

标签: java concurrency filelock

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

1 个答案:

答案 0 :(得分:2)

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

// 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()"
...

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

相关问题