Java 7 Watch Service ENTRY_CREATE triggered before file is written
Asked Answered
S

2

9

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, but sometimes (not always) when a WatchEvent of ENTRY_CREATE occurs, the file has not yet been written to the disk.

I've confirmed this by creating a new File() of the directory the watch service is registered to along with the path of the file and checking the exists() method, so it seems that the OS is triggering the create event before the file is actually created.

This question appears to be the same issue, but from the folder's point of view.

Any way I can work around this?

Seychelles answered 8/1, 2016 at 7:40 Comment(2)
See this answer -- looks like you're suffering from the same problem.Wishywashy
It does - I'll leave this up for a bit in case any better solutions emerge though.Seychelles
B
15

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( );
Barrio answered 11/1, 2016 at 10:3 Comment(1)
I can only award the bounty in 20 hours, I'll do so then.Seychelles
R
-1

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.

Riant answered 8/1, 2016 at 9:18 Comment(1)
Problem is, I need to keep it as responsive as possible so I'm looking for a way where I minimize the delay.Seychelles

© 2022 - 2024 — McMap. All rights reserved.