views:

180

answers:

2

Hi all,

I would like to know how to efficiently implement filesystem changes in java? Say I got a file in a folder and modify that file. I would like to be notified by java about this change as soon as possible(no frequently polling if possible.).

Because I think I could call java.io.file.lastModified every few seconds but I don't like the sound of that solution at all.

alfred@alfred-laptop:~/testje$ java -version
java version "1.6.0_18"
Java(TM) SE Runtime Environment (build 1.6.0_18-b07)
Java HotSpot(TM) Server VM (build 16.0-b13, mixed mode)

Many thanks, Alfred

+1  A: 

I doubt that there is a pure java way to do this. Operating systems offer APIs to monitor file system a activity. You will probably need to call those APIs.

Jim Blizard
I have not looked at it at all but think it is actually part of what they address in the new file system APIs in Java7. At the end of the day it will of course need support from the file system or OS itself.
Fredrik
+6  A: 

Take a look at JNotify, which performs this type of monitoring.

Java 7 will have some more advanced APIs (WatchService) for this sort of work which will eliminate polling on the OSes that support this.

Brian Agnew
IIRC, JNotify requires OS specific DLLs. While likely not as performant (yeah, not yet a real word), JPoller provides a pure Java implementation.
Kaleb Pederson
So it is always a little hack I guess until using Java7 because I think Jpoller polls like crazy. JNotify isn't native..
Alfred
Not quite sure what you mean by JNotify not being native. It does require OS-specific DLLs/libraries.
Brian Agnew
@Brian: I am going to look closer at JNotify, but from what I read so far from JNofity is that it uses system specific solution. I hoped I missed something somewhere and just put a single jar in my classpath(in netbeans). Next call a function with a callback or something and get notified.
Alfred