I've locked a file using a FileLock in Java, but now I can't read to or write from it. What do I do?
Asked
Active
Viewed 349 times
0
-
1Define "can't". What happens instead? – user207421 Aug 15 '12 at 22:48
1 Answers
2
While there may be many potential solutions to this issue, I've found that the following works quite nicely:
// 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()"
...
I found this issue very frustrating when I encountered it, so I thought I'd share my solution with others that might need it.

Dylan Knowles
- 2,726
- 1
- 26
- 52