Thursday, February 3, 2011

How to read file without locking in Java

In java, we can read or write to a file without acquiring locks to it. These are mostly used for log files. Recently I was tying to mimic the tail command (of Linux) in java and wrote a simple program below.

Using we can read/write to a file without obtaining locks. Let me demonstrate with example step by step how it works.

RandomAccessFile accessFile = new RandomAccessFile(file, "r");

Create an instance of the RandomAccessFile by either passing or a path of a file. The second constructor argument is the type of access needed. In this case it is read only "r". If you want to make it read/write pass "rw". Like Buffers of java.nio package, this class also works with the pointers. it reads the bytes and move the pointer as it progresses. The current pointer gives the information about how much of the file have bean read or has to be read.

public void print(OutputStream stream) throws IOException {
    long length = accessFile.length();
    while (accessFile.getFilePointer() < length) {