is it possible to monitor folder using java code?
start a thread to scan the folder changes,which could be create,delete,update files in this folder or something else happen,like last updated.
but in this case, you have to control thread loop. if this thread loop is not controlled well,then it would be a waste of cpu and may cause a fat开发者_StackOverflow中文版al problem.
or,is there any framework or some demo code to do this ? hope we could find a better way to do this. thank u very much.
JDK7's java.nio.file package has a WatchService
to support file change notification. You can use it to monitor a directory for changes. This uses native facilities where available, otherwise it uses a primitive mechanism such as polling. Here is a post on it.
For now, you can try jpathwatch, which is an implementation of the WatchService
interface and uses native OS functions, instead of polling.
Your thought is not bad.
To monitor a folder in java, the usual way is to control it in a separate thread using a loop. In order to save CPU, you can use a tempo (check every n seconds).
Then, to notify a change from this thread, you can use the "Observer" design pattern.
The pure Java way would be to spun off a thread that polls the directory and tracks changes.
A more efficient way would be to write an OS specific library (You'll probably have to do it in C or C++) that can use OS specific tools to obtain a notification (via a callback into your Java code), and call it via JNI
No it is not. There are some libraries doing the polling for you such as:
http://mindprod.com/jgloss/filemonitor.html that is free and http://www.teamdev.com/jxfilewatcher that is not free
"Ideally, you would like to avoid polling and have instant notification of changes. To do this would require OS-specific JNI code to hook into the native file system. This would also require high privilege."
精彩评论