*
The moose likes I/O and Streams and the fly likes Regarding Lock on file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Regarding Lock on file" Watch "Regarding Lock on file" New topic
Author

Regarding Lock on file

vikasids sharma
Ranch Hand

Joined: Aug 01, 2003
Posts: 157
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


Thanks
Vikas Sharma
SCJP(1.4)
Eric Gero
Ranch Hand

Joined: Jul 20, 2005
Posts: 73
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 ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Regarding Lock on file
 
Similar Threads
FileLock in XP environment
Reading from a file that may be in use by another program
how to lock a file?
FileLock on Windows
only one program can run at the moment