16

Java 7 introduced WatchService for monitoring file systems continuously. Is there a backport for Java 6 ?

Are there pure Java libraries with similar features ?

paradigmatic
  • 40,153
  • 18
  • 88
  • 147

3 Answers3

15

yes, of course. Apache VFS does exactly this. you can find it under http://commons.apache.org/vfs/. It's a pure java library that can monitor files and it's pretty easy to use:

FileSystemManager manager = VFS.getManager();
FileObject file= manager.resolveFile("c:/MyFile.txt");

DefaultFileMonitor fm = new DefaultFileMonitor(new MyListener());
fm.setDelay(5000);
fm.addFile(file); 
fm.start();

the code above will monitor the file c:/MyFile.txt. if it changes, the object new MyListener() is called.

Oliv
  • 10,221
  • 3
  • 55
  • 76
Thomas Uhrig
  • 30,811
  • 12
  • 60
  • 80
  • 17
    DefaultFileMonitor seems to be a poller, not an equivalent to WatchService which would receive notifications from the OS without polling. – Jesse Glick Dec 09 '11 at 15:21
5

A pure Java library for this is impossible; you need a native component if you want to avoid polling.

http://wiki.netbeans.org/NativeFileNotifications gives some information about both the available native APIs and various Java libraries wrapping them.

Jesse Glick
  • 24,539
  • 10
  • 90
  • 112
4

Jetbrains IntelliJ IDEA has a component 'Virtual File System' which fires a native file system watcher notifying underlying file system changes back to IDEA. For two years Jetbrains has been releasing an open source version which should be containing the component. It works with Java 6.

It's released under Apache 2.0 license as claimed in the FAQ page.

Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148