Question

Trying to read a log file line-by-line (in Java). This log file is being written to simultaneously by another process (non-java program).

I have 2 approaches -

  1. BufferedReader (BufferedReader br = new BufferedReader(new FileReader(logFile));)
  2. RandomAccessFile (RandomAccessFile accessFile = new RandomAccessFile(logFile.getAbsolutePath(), "r");)

Do both these approaches cause the file to be locked till i call the 'close' method on the BufferedReader/RandomAccessFile object ?

Are there any other ways (Java) to read a file in such a way that the file is not locked/blocked for other processes/programs ?

PS - in all my searches, I have come across multiple answers/solutions (old and new) to this problem. I just wish to seek clarification/closure on this issue.

Was it helpful?

Solution 2

BufferedReader is preferable to RandomAccessFile on performance grounds, but neither of them will lock the file at all unless the operating system kindly does so for you, in which case closing the file will release it.

However the operating system may also kindly prevent you reading the file at all if someone else is writing to it.

Reading a sequential file while another process is writing to it is not good design. You shouldn't really be reading log files at all. Log files are for humans. You should be using a database.

OTHER TIPS

Take a look at this: Java: opening and reading from a file without locking it

If the non-Java process has an exclusive lock on the file when it is writing, no other process may be able to read it. Of course, this may vary slightly with operating system. You might want to look at what the operating system says about the file lock when the non-Java process is running.

If a shared lock is available, then java.nio may allow more control over the locking behaviour: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top