Java 7 Watch Service ENTRY_CREATE triggered before file is written

后端 未结 2 1572
失恋的感觉
失恋的感觉 2020-12-16 22:09

I have a watch service watching a directory. Once files are created, I\'m processing the directory and updating a tree view.

This works fine on ENTRY_DELETE

相关标签:
2条回答
  • 2020-12-16 22:36

    The event is triggered when a file is created. The file needs to be created before it can be written to. A file doesn't simply appear once it is fully written, it appears once it is created.

    What you can do is once you get the creation event:

    • Create a File object to point to the file
    • Create a java.nio.channels.FileChannel for random access using RandomAccessFile with rw mode (so read & write access)
    • Lock the channel. This will block until the file is free for read/write access (read the more general Lock method for more info)
    • When the lock is acquired, your file was released by the process that wrote the file

    A simplified example:

    File lockFile = new File( "file_to_lock" );
    FileChannel channel = new RandomAccessFile( lockFile, "rw" ).getChannel( );
    channel.lock( );
    
    0 讨论(0)
  • 2020-12-16 22:53

    I had the same issue, I added few seconds delay once the event is created before processing. Since Other application used to write the file and it used to take couple of seconds to flush the content and release the file.

    0 讨论(0)
提交回复
热议问题