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.
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;
32 * Monitors a directory for changes.
34 * @author Erik Brakkee
36 public class DirectoryMonitor {
40 private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
45 private File directory;
50 private FileFilter filter;
55 private Listener listener;
60 private Map<File, Date> contents;
63 * Creates a new DirectoryMonitor object.
65 * @param aDirectory DOCUMENT ME!
66 * @param aFilefilter DOCUMENT ME!
67 * @param aListener DOCUMENT ME!
69 public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
71 directory = aDirectory;
73 if (!directory.isDirectory()) {
74 throw new IllegalArgumentException("Directory '" + directory
75 + "' does not exist");
80 contents = new HashMap<File, Date>();
84 * Polls the directory for changes and notifies the listener of any
85 * changes. In case of any exceptions thrown by the listener while
86 * handling the changes, the next call to this method will invoked the
87 * listeners again for the same changes.
90 LOG.debug("Polling " + directory);
92 Map<File, Date> newContents = new HashMap<File, Date>();
93 File[] files = directory.listFiles(filter);
95 // Check deleted files.
96 Set<File> deletedFiles = new HashSet<File>(contents.keySet());
98 for (File file : files) {
100 if (contents.containsKey(file)) {
101 deletedFiles.remove(file);
106 for (File file : deletedFiles) {
107 listener.fileDeleted(file);
110 for (File file : files) {
112 if (contents.containsKey(file)) {
113 Date oldDate = contents.get(file);
115 if (file.lastModified() != oldDate.getTime()) {
116 listener.fileChanged(file);
121 newContents.put(file, new Date(file.lastModified()));
123 listener.fileCreated(file);
124 newContents.put(file, new Date(file.lastModified()));
129 contents = newContents;
132 public static interface Listener {
133 void fileChanged(File aFile);
135 void fileCreated(File aFile);
137 void fileDeleted(File aFile);