Firstly, I have checked java.io.IOException: The process cannot access the file because another process has locked a portion - when using IOUtils.copyLarge() in Windows. My question is not about finding whether a file is open or not.
I have a Java application A that is writing log files to the disk. At a given time, there are a large number of files that are written and closed by the A, and few files which are still open, and are being written by A.
I have this second Java application B, which need to read the logs sometimes, and it does. But the problem is, in case the file is open by A, B will spill the error java.io.IOException: The process cannot access the file because another process has locked a portion.
The code that reads the file from B looks like this:
void readFile(Path filePath) {
FileInputStream fis = new FileInputStream(filePath.toFile());
byte[] buffer = new byte[1024]
for (int len; (len = fis.read(buffer)) != -1) {
// do things with the read bytes
}
}
I have no control over application A's code. Neither can I determine when application A will release the file. It could be 24+ hours. So I need B to read the file while it's open (if it can be done at all).
I can, however change B's code. Is there any way I can change the above code such that B can read the contents of the locked file? Note that B only needs read access to the files.