Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Lock on file

 
vikasids sharma
Ranch Hand
Posts: 157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

Can we lock the file for reading-writing i.e if one java program reads the file and no other program could read before the first program complete writing it.

Thanks
Vikas
 
Eric Gero
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe the actual "locking" depends on the operating system. The lock may be implemented as an advisory lock, so if other apps don't check for it, they won't know the file is locked.

try {
File file = new File("myfile");
FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();

FileLock myLock = fileChannel.lock();

try {
myLock = fileChannel.tryLock();
} catch (OverlappingFileLockException e) {

}

myLock.release();

fileChannel.close();
} catch (Exception e) {
}

Eric
[ April 14, 2007: Message edited by: Eric Gero ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic