我在Java中使用FileLock锁定了一个文件,但现在我无法读取或写入它。我该怎么办?
答案 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()"
...
当我遇到这个问题时,我发现这个问题非常令人沮丧,所以我想我会与可能需要它的其他人分享我的解决方案。