Thursday, August 20, 2009

Java Source Code to lock a file

Below source code is the simple example of how to lock a file. The below program will not allow you to delete the created file or to edit the created file for 1 min. I will use FileChannel and FileLock class to achieve that.

API Source:

http://java.sun.com/javase/6/docs/api/java/nio/channels/FileLock.html
http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
*
* @author Snehanshu
*/
public class FileLockDemo {

/** Creates a new instance of FileLockDemo */
FileLockDemo() {
}

private void doLockFile() {
try{
File file = new File("./FileLockDemo.txt");
FileLock lock = null;
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write("File is being locked");
bufferedWriter.close();

FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
System.out.println("Locking the file");
lock = channel.lock(0, Long.MAX_VALUE, true); // Create a shared lock on the file.

// This section of code will lock the file for 1 mins [60 secs = 60000 milliseconds].
//For those 60 secs, you will not be able to delete or save the file after editing.
System.out.println("Wait for 60 secs for the program to unlock the file");
try {
Thread.sleep(60000);
} catch (InterruptedException ie) {
ie.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Releasing the lock of the file");
if (lock != null && lock.isValid()) {
lock.release(); // Lock is being released
}
} catch(FileNotFoundException fNFE) {
fNFE.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
FileLockDemo fileLockDemo = new FileLockDemo();
fileLockDemo.doLockFile();
}

}

No comments:

Total Pageviews