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;
20 import java.io.FileFilter;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.HashSet;
27 import java.util.logging.Logger;
30 * Monitors a directory for changes.
31 * The currernt implementation only checks files not directories and does not check for
32 * modifications in subdirectories.
34 * @author Erik Brakkee
36 public class DirectoryMonitor {
37 private static final Logger LOG = Logger.getLogger(DirectoryMonitor.class.getName());
39 private File directory;
41 private FileFilter filter;
43 private Listener listener;
45 private Map<File, Date> contents;
48 * Creates a new DirectoryMonitor object.
51 public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
53 directory = aDirectory;
55 if (!directory.isDirectory()) {
56 throw new IllegalArgumentException("Directory '" + directory +
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
68 * changes, the next call to this method will invoked the listeners again
69 * for the same changes.
72 LOG.fine("Polling " + directory);
74 Map<File, Date> newContents = new HashMap<File, Date>();
75 File[] files = directory.listFiles(filter);
77 // Check deleted files.
78 Set<File> deletedFiles = new HashSet<File>(contents.keySet());
80 for (File file : files) {
82 if (contents.containsKey(file)) {
83 deletedFiles.remove(file);
88 for (File file : deletedFiles) {
89 listener.fileDeleted(file);
92 for (File file : files) {
94 if (contents.containsKey(file)) {
95 Date oldDate = contents.get(file);
97 if (file.lastModified() != oldDate.getTime()) {
98 listener.fileChanged(file);
103 newContents.put(file, new Date(file.lastModified()));
105 listener.fileCreated(file);
106 newContents.put(file, new Date(file.lastModified()));
111 contents = newContents;
115 * Listener interface to be provided by users of the directory monitor to get notified of
118 * @author Erik Brakkee
120 public static interface Listener {
122 * @param aFile File that has changed.
124 void fileChanged(File aFile);
127 * @param aFile File that was created.
129 void fileCreated(File aFile);
132 * @param aFile File that was deleted.
134 void fileDeleted(File aFile);