Barry Wei
Barry Wei

Reputation: 141

is it possible to monitor folder using java code?


is there anyone know how to monitor a folder using java? or anyone could gave me a point that how could i start this. here's my thought about it.

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

Upvotes: 6

Views: 7624

Answers (4)

dogbane
dogbane

Reputation: 274532

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.

Upvotes: 13

pauljwilliams
pauljwilliams

Reputation: 19225

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

Upvotes: 1

Benoit Courtine
Benoit Courtine

Reputation: 7064

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.

Upvotes: 1

Manuel Selva
Manuel Selva

Reputation: 19050

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

Upvotes: 0

Related Questions