Friday, September 17, 2010

Folder Locking using Java

Hi,
  Here you can find HOW TO LOCK A FOLDER using java. In this example i passed the images folder as an input to lock. Whenever you passed a file path as an input then the folder which contains the input file is locked. Means no one can be able to modify/delete the file contents. 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;


public class FolderLocking {
    public static void main(String[] args) {

        //Pass the Path of the images folder
        String imagePath = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg";
        RandomAccessFile file = null;

        File parentFile = new File(imagePath).getParentFile();
        int length = parentFile.listFiles().length;
        File fileList[] = parentFile.listFiles();
        FileLock fileLocker[] = new FileLock[length];
        for(int i=0; i<fileList.length; i++)
        {
            try {
                file = new RandomAccessFile(fileList[i],"rws");
                FileChannel fileChannel = file.getChannel();

                fileLocker[i] = fileChannel.tryLock();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the Key.......");
        try {
            if(br.readLine().equals("Open"))
            {
                for(int j=0;j<fileLocker.length;j++)
                    {
                        if(fileLocker[j] != null)
                            fileLocker[j].release();
                    }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1 comment:

  1. Hi Uday,

    fileLocker[i] = fileChannel.tryLock();

    In your code instead of tryLock() can we use lock() method?

    I read that

    tryLock() - will not wait its thread till gets lock on the file.

    lock() - will blocks the thread till application gets locks on the file.

    Also can you please tell me exact situations in which we can apply each of it?

    Thanks

    Satyaprasad

    ReplyDelete