File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FileLock on Windows

 
Ned Miles
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20375
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47253
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to JavaRanch
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic