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