Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to track a change in a folder in Java?

Tags:

java

directory

I have a set of source folders. I use a Java class to build the distribution file out of these folders. I'd like to write another little class in Java which runs every half a second, checks if any of the files in the folders have changed, and if yes, run the building class.

So, how do I detect easily that a folder has been modified ?

like image 654
glmxndr Avatar asked Jun 23 '09 11:06

glmxndr


People also ask

Can we monitor a directory for adding new files in Java?

Create a WatchService "watcher" for the file system. For each directory that you want monitored, register it with the watcher. When registering a directory, you specify the type of events for which you want notification. You receive a WatchKey instance for each directory that you register.

What method is used to read the content of a folder Java?

The readString() method of File Class in Java is used to read contents to the specified file.

How do I find folder modification history?

Right-click a file or folder in the project and click Show History. In the Change Explorer view, open a change set, right-click a file or folder in the change set, and select Show History.


2 Answers

I think you will need to check the directory and subdirectory modfication times (for files being added/removed) and the file modification times (for the changes in each file).

Write a recursive routine that checks a directory for it's modification time and if it's changed, plus each files. Then checks the directory contents, and call recursively for any subdirectories. You should just be able to check for any modification times greater than when you last ran the check.

See File.lastModified()

EDIT: Since I wrote the above, Java 7 came out with its directory watching capability.

like image 56
Brian Agnew Avatar answered Sep 18 '22 19:09

Brian Agnew


Here a list of possible solutions and an example of simple File/Folder Watcher.

like image 44
RealHowTo Avatar answered Sep 20 '22 19:09

RealHowTo