is it possible to monitor folder using java code?

和自甴很熟 提交于 2019-11-30 14:08:55

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.

dogbane

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.

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."

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!