Java file lock


 

Java file lock

In this section, you will learn how to lock a file.

In this section, you will learn how to lock a file.

Java file lock

In this section, you will learn how to lock a file.

The behavior of the file lock is platform-dependent. The file lock is advisory on some platforms, means unless an application checks for a file lock, it will not be prevented from accessing the file while the file lock is mandatory on other platforms, means file lock prevent any application from accessing file.  It is important to understand that File locking is hugely dependent on the native operating system on which the program is executing. Previously there was no direct support in Java for locking a file but now, you can achieve the file locking by using the New I/O API (nio).

Java provides lock and tryLock() methods in FileChannel class for getting a lock over the file object. In the given program, we have used lock() method to lock the file 'file.txt'. This method blocks the thread until it gets a lock on the file. Now to ensure that the file is locked,  we have called the method accessFile() which tries to read the file contents but it throws an exception.

Here is the code:

import java.io.*;
import java.nio.channels.*;

public class FileLockExample {
	public static void main(String[] args) throws Exception {
		try {
			RandomAccessFile file = new RandomAccessFile("C:/file.txt", "rw");
			FileChannel fileChannel = file.getChannel();
			FileLock fileLock = fileChannel.tryLock();
			if (fileLock != null) {
				System.out.println("File is locked");
				accessFile();
			}
		} catch (Exception e) {
		}
	}

	public static void accessFile() {
		try {
			String line = "";
			BufferedReader br = new BufferedReader(
					new FileReader("C:/file.txt"));
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

Ads