2 * Copyright 2005-2010 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.
16 package org.wamblee.io;
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
22 import java.io.FileFilter;
24 import java.util.Date;
25 import java.util.HashMap;
26 import java.util.HashSet;
31 * Monitors a directory for changes.
32 * The currernt implementation only checks files not directories and does not check for
33 * modifications in subdirectories.
35 * @author Erik Brakkee
37 public class DirectoryMonitor {
38 private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
40 private File directory;
42 private FileFilter filter;
44 private Listener listener;
46 private Map<File, Date> contents;
49 * Creates a new DirectoryMonitor object.
52 public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
54 directory = aDirectory;
56 if (!directory.isDirectory()) {
57 throw new IllegalArgumentException("Directory '" + directory +
63 contents = new HashMap<File, Date>();
67 * Polls the directory for changes and notifies the listener of any changes.
68 * In case of any exceptions thrown by the listener while handling the
69 * changes, the next call to this method will invoked the listeners again
70 * for the same changes.
73 LOG.debug("Polling " + directory);
75 Map<File, Date> newContents = new HashMap<File, Date>();
76 File[] files = directory.listFiles(filter);
78 // Check deleted files.
79 Set<File> deletedFiles = new HashSet<File>(contents.keySet());
81 for (File file : files) {
83 if (contents.containsKey(file)) {
84 deletedFiles.remove(file);
89 for (File file : deletedFiles) {
90 listener.fileDeleted(file);
93 for (File file : files) {
95 if (contents.containsKey(file)) {
96 Date oldDate = contents.get(file);
98 if (file.lastModified() != oldDate.getTime()) {
99 listener.fileChanged(file);
104 newContents.put(file, new Date(file.lastModified()));
106 listener.fileCreated(file);
107 newContents.put(file, new Date(file.lastModified()));
112 contents = newContents;
116 * Listener interface to be provided by users of the directory monitor to get notified of
119 * @author Erik Brakkee
121 public static interface Listener {
123 * @param aFile File that has changed.
125 void fileChanged(File aFile);
128 * @param aFile File that was created.
130 void fileCreated(File aFile);
133 * @param aFile File that was deleted.
135 void fileDeleted(File aFile);