Java File Locking in Windows
Posted on 2003-11-18
I am trying to find out whether or not a file has a lock in Windows. The overall goal is to find new files in a directory so I can process them. The files are transferred into the directory via FTP. The problem is that I need the file to be completely transferred before I process it, but I can't find a way to figure out whether it's completed or not. The ftp logs do not store the right information for me to use it effectively. I have tried to find out whether the file had a lock or not, or to see if I could open it for writing, and it always allows me to. Interesting enough, while it is still being transferred, I cannot move the file, whether is explorer or Java-- so I know there is a lock somewhere, but I just can't figure out how to read it in Java!
How can I read the lock that prevents the file from being moved without actually trying to move the file?
File f = new File("test");
f.canRead(); // Always returns true
f.canWrite(); // Always returns true
f.renameTo(new File("newFileName")); // returns false when the file is being transferred (helpful)
RandomAccessFile raf = new RandomAccessFile("junk.dat", "rw");
FileChannel channel = raf.getChannel();
FileLock lock = channel.lock(); // always succeeds