Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes FileLock on Windows Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "FileLock on Windows" Watch "FileLock on Windows" New topic
Author

FileLock on Windows

Ned Miles
Greenhorn

Joined: Sep 11, 2010
Posts: 1
I have a question regarding file locking on Windows and the Java API for FileLock (I tried this on both Windows XP and Windows Server 2003). Let's assume I have two programs (different JVMs possibly on different machines) that access the same file (test.txt)- one for reading and the other for writing. In an effort to do things correctly, the reading program is going to try and get a shared lock prior to reading. Conversely, the writing program will get an exclusive lock prior to writing.

Here is sample code from the reading program:



Here is the sample code from the writing program:




If the reading program is run first, it obtains the lock and then sleeps indefinitely. I then run the writing program and it blocks attempting to obtain the exclusive lock, which I would expect. However, by executing the first line successfully (new FileOutputStream("test.txt")), it has already overwritten the file. Interestingly, if you remove the logic to obtain the lock from the writing program, you get an exception at fos.write() line stating that the file is locked by another process. This is great but, again, the file has already been truncated to 0 bytes by invoking new FileOutputStream().

It seems strange to me, especially on Windows, that it would prevent you from writing to the file but allow you to completely overwrite the file. Any information anyone could provide would be appreciated. It is actually a little difficult to code around this because in order to get a FileLock you need and FileChannel, and in order to get a FileChannel you need a FileOutputStream. However, I can't get a FileOutputStream without overwriting the file. I realize I can use the RandomAccessFile to get a FileChannel but due to existing code, I need to get a FileOutputStream eventually.

Thanks in advance,
Ned
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19684
    
  20

You could try creating a FileOutputStream in append mode (so it will not truncate the file) and then set the position to 0, but I haven't tested if that will work.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38517
    
  23
And welcome to JavaRanch
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: FileLock on Windows