2 * Copyright 2006 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.wamblee.io;
20 import java.io.FileFilter;
21 import java.util.Date;
22 import java.util.HashMap;
23 import java.util.HashSet;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
31 * Monitors a directory for changes.
33 * @author Erik Brakkee
35 public class DirectoryMonitor {
37 private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
39 public static interface Listener {
41 void fileChanged(File aFile);
43 void fileCreated(File aFile);
45 void fileDeleted(File aFile);
48 private File _directory;
49 private FileFilter _filter;
50 private Listener _listener;
51 private Map<File, Date> _contents;
53 public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
55 _directory = aDirectory;
56 if (!_directory.isDirectory()) {
57 throw new IllegalArgumentException("Directory '" + _directory
58 + "' does not exist");
60 _filter = aFilefilter;
61 _listener = aListener;
62 _contents = new HashMap<File, Date>();
66 * Polls the directory for changes and notifies the listener of any changes.
67 * In case of any exceptions thrown by the listener while handling the changes,
68 * the next call to this method will invoked the listeners again for the same changes.
71 LOG.debug("Polling " + _directory);
72 Map<File, Date> newContents = new HashMap<File, Date>();
73 File[] files = _directory.listFiles(_filter);
75 // Check deleted files.
76 Set<File> deletedFiles = new HashSet<File>(_contents.keySet());
77 for (File file : files) {
79 if (_contents.containsKey(file)) {
80 deletedFiles.remove(file);
84 for (File file : deletedFiles) {
85 _listener.fileDeleted(file);
88 for (File file : files) {
90 if (_contents.containsKey(file)) {
91 Date oldDate = _contents.get(file);
92 if (file.lastModified() != oldDate.getTime()) {
93 _listener.fileChanged(file);
97 newContents.put(file, new Date(file.lastModified()));
99 _listener.fileCreated(file);
100 newContents.put(file, new Date(file.lastModified()));
105 _contents = newContents;