Can't read or write from a locked file in Java
-
26-06-2021 - |
Question
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?
Solution
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow