0

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

4

1 回答 1

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

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

于 2012-08-15T21:52:05.830 回答