Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 680
Barry Wei Avatar asked Sep 28 '10 08:09

Barry Wei


1 Answers

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.

like image 147
dogbane Avatar answered Oct 07 '22 00:10

dogbane