javafilelock

File Locking in java


I have a list of files in a folder, I want to lock a specific file(user send me the name of the file to be locked), which i am doing as below:

try {

    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    FileLock lock = channel.lock();
    try {
        lock = channel.tryLock();
    } catch (OverlappingFileLockException e) {
        // File is already locked 
    }

} catch (Exception e) {
}

And if another user wants to see the list of files i have to tell them the status of file which is locked and which is unlocked

   File folder = new File("E:\\folder_to_LIST_OF_FILES");
            File[] listOfFiles = folder.listFiles();

            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    FilesDto returnDto = new FilesDto();
                    returnDto.setFileName(FilenameUtils.removeExtension(listOfFiles[i].getName()));

                    // Check File Status if file is Locked or unlocked

                    if (lock==null) {
                        returnDto.setStatus("unlocked");
                        returnDto.setFilePath(listOfFiles[i].getAbsolutePath());

                    } else {
                        returnDto.setStatus("Locked");
                    }

                    returnDtoList.add(returnDto);
                }
            }

These two snippets are from different API's. How To Check the status of File it is locked or unlocked?


Solution

  • The documentation on FileLock class says:

    This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.

    So it seems that you could just use same code as in your first snippet:

    File folder = new File("E:\\folder_to_LIST_OF_FILES");
    File[] listOfFiles = folder.listFiles();
    
    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()) {
            FilesDto returnDto = new FilesDto();
            returnDto.setFileName(FilenameUtils.removeExtension(listOfFiles[i].getName()));
    
            File file = new File("filename");
            FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
            FileLock lock;
            try {
                lock = channel.tryLock();
            } catch (OverlappingFileLockException e) {
                // File is already locked 
            }
    
            if (lock==null) {
                returnDto.setStatus("unlocked");
                returnDto.setFilePath(listOfFiles[i].getAbsolutePath());
    
            } else {
                lock.release();
                returnDto.setStatus("Locked");
            }
    
            returnDtoList.add(returnDto);
        }
    }