javafilefile-lockingrandomaccessfile

Read external log file without creating file-lock


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 untill I call the close method on the BufferedReader/RandomAccessFile object?

Are there any other ways in 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.


Solution

  • 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.