简体   繁体   中英

Java: Watching a Directory for Changes

I want to create a listener to detect directory change recursively (the main directory and its subdirectories). After a web search I found this link that explains the use of the class WatchService from the Package java.nio.file that api exactly meets my needs but unfortunately it is only available in Java 7! Then I return to search again in order to find a framework that allows the same and is compatible java 5 and java 6 but again there was a problem, because recursion is available for Windows and my application should use Linux!! Can you offer me a solution: another framework, a way to do..

I think you did a good discovery job and found a wonderful library jpathwatch. I do not understand what was your problem with recursion: I have not seen any restriction for linux in this library documentation.

But if for some reason jpathwatch cannot help you on linux, it is not a problem: you can run du command yourself. See this reference: http://linux.about.com/library/cmd/blcmdl1_du.htm

If I were you I probably do the following: write simple script that runs du in loop. Then run this script from java from separate thread that is contiguously reading the script's output and analyses it.

This is a kind of functionality that requires support of JVM or a native library, such as the one you've found for Windows. If you can't find anything in Java for Linux, I suggest asking for a binary Linux library (in a different question) and then build a Java native class on top of that.

I hope other people will help you better.

To do this on Linux you need to use Java 7, or a native library that uses inotify . Have you considered the JNotify library ? It looks like it handles recursion into subdirectories, including newly created ones.

Have a look at http://download.oracle.com/javase/tutorial/essential/io/notification.html

"The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed."

Update: Ooops, just realized you already saw this. I didn't realize this was only in Java 7 :-(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM