1

I have a simple file monitor setup that watches one file so I get notified when the contents of that file changes, added, or deleted. But when the file gets deleted I never get notified when it gets added back. Here is a snippet of my code:

String properyPath = "/some/directory/somexml.xml";
FileSystemManager fsManager;
fsManager = VFS.getManager();
FileObject listendir = fsManager.resolveFile( propertyPath );
DefaultFileMonitor fm = new DefaultFileMonitor( this );
fm.setRecursive( true );
fm.addFile( listendir );
fm.start();

When the propertyPath file gets deleted I get notified in my fileDeleted implementation, but the fileAdded method never gets called when I recreate the file again. Is this normal? If so, how do I set it up to get notified on adds after a delete?

darrickc
  • 1,872
  • 6
  • 27
  • 38

3 Answers3

1

It looks like you're affected by this issue. As stated in the ticket you can try to set a zero delay:

fm.setDelay(0); 

or try a patched DefaultFileMonitor. Small delays, however, may have a performance impact if you're going to watch for too many files simultaneously.

Jk1
  • 11,233
  • 9
  • 54
  • 64
0

Thanks Jk1 for pointing me to the issue. The answer is found here.

In summary, the FileMonitorAgent class in vfs removes the listener when a file gets deleted. (see the check method) below is the important block:

// If the file existed and now doesn't
if (this.exists && !this.file.exists())
{
  this.exists = this.file.exists();
  this.timestamp = -1;

  // Fire delete event

  ((AbstractFileSystem)
     this.file.getFileSystem()).fireFileDeleted(this.file);

  // Remove listener in case file is re-created. Don't want to fire twice.
  if (this.fm.getFileListener() != null)
  {
     this.file.getFileSystem().removeListener(this.file,
        this.fm.getFileListener());
  }

  // Remove from map
  this.fm.queueRemoveFile(this.file);
}

The link supplies a solution that has been submitted to vfs. I think the only solution at this point is to spawn a thread that re-adds the file to vfs after a few seconds. You have to sleep a few seconds because you get notified (via fireFileDeleted) and then the vfs code clears the listener, so you can re-add the listener until after you get notified and the vfs code clears the existing listener.

darrickc
  • 1,872
  • 6
  • 27
  • 38
0

I have faced this same problem recently.

What I did to solve it was:

@Override
public void fileDeleted(FileChangeEvent arg0) throws Exception {
    if (arg0.getFile().getName().getBaseName().equals("ErrLog.txt")) {
        File removedFile = new File(arg0.getFile().getName().getPath());
        removedFile.getParentFile().mkdirs();
    }
}

In my case, I was monitoring the parent directory of ErrLog.txt. This directory was removed.