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.
33 * @author Erik Brakkee
35 public class DirectoryMonitor {
36 private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
38 private File directory;
40 private FileFilter filter;
42 private Listener listener;
44 private Map<File, Date> contents;
47 * Creates a new DirectoryMonitor object.
50 public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
52 directory = aDirectory;
54 if (!directory.isDirectory()) {
55 throw new IllegalArgumentException("Directory '" + directory +
61 contents = new HashMap<File, Date>();
65 * Polls the directory for changes and notifies the listener of any changes.
66 * In case of any exceptions thrown by the listener while handling the
67 * changes, the next call to this method will invoked the listeners again
68 * for the same changes.
71 LOG.debug("Polling " + directory);
73 Map<File, Date> newContents = new HashMap<File, Date>();
74 File[] files = directory.listFiles(filter);
76 // Check deleted files.
77 Set<File> deletedFiles = new HashSet<File>(contents.keySet());
79 for (File file : files) {
81 if (contents.containsKey(file)) {
82 deletedFiles.remove(file);
87 for (File file : deletedFiles) {
88 listener.fileDeleted(file);
91 for (File file : files) {
93 if (contents.containsKey(file)) {
94 Date oldDate = contents.get(file);
96 if (file.lastModified() != oldDate.getTime()) {
97 listener.fileChanged(file);
102 newContents.put(file, new Date(file.lastModified()));
104 listener.fileCreated(file);
105 newContents.put(file, new Date(file.lastModified()));
110 contents = newContents;
113 public static interface Listener {
114 void fileChanged(File aFile);
116 void fileCreated(File aFile);
118 void fileDeleted(File aFile);