2

I implemented JNotify to determine when a new file arrives in a particular directory, and, when a file arrives, to send the filename over to another function, as follows:

    public class FileDetector {
            MessageProcessor mp;
            class Listener implements JNotifyListener {
                    public void fileCreated(int wd, String rootPath, String name) {
                            print("created " + rootPath + " : " + name);
                            mp.processMessage(rootPath + "\\" + name);
                    }
            }
    }

The function mp.processMessage tries to open the file, but I keep getting an error that the file is in use by another process. However, as the file has just been created, the only other process which might be using it is JNotify.

I put a couple of print statements, and it appears that the function mp.processMessage is being called before the listener's print function. Does anyone have a suggestion for how I might resolve this, beyond putting the entire message processing inside the listener class?

Elie
  • 13,253
  • 22
  • 70
  • 127
  • What OS and filesystem is the file being created in? Is the file created by another process? Does the other process create the file and then open it for writing? – Bringer128 Jul 08 '11 at 05:00
  • Windows. I was just copying a file into the directory, or using FTP to move the file there. – Elie Jul 08 '11 at 16:33

3 Answers3

1

@Eile What I think is As soon as one process is copying the file, you are trying to read it, 100 ms delay will complete the copy first n then you can read the file easily.

Sunny Gupta
  • 6,219
  • 14
  • 47
  • 80
0

Here's what I've done so far - I added into mp.processMessage() a 100 millisecond delay before trying to open the file, and have had no issues with it. However, I am still puzzled as to why that would be necessary, and whether or not there is a better solution to this issue.

Elie
  • 13,253
  • 22
  • 70
  • 127
0

I have tried this and have found that an arbitrary delay didn't work well for me. What I did was create a DelayQueue. I added each observed new file to the queue with a 100ms delay. When the delay expired I checked if the file was readable/writable. If is was, I popped it from the queue. If not, I readded it to the queue with another 100ms delay. To check if it was readable/writable I attempt to open a FileInputStream to the file. If no exception, I close the stream and pop the file.

I am hoping that nio.2 (jsr 203) does not have this same issue. If you can use Java 7 you might want to give it a try.

John B
  • 30,460
  • 6
  • 67
  • 92