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;
19 import java.io.FileFilter;
21 import java.util.Date;
22 import java.util.HashMap;
23 import java.util.HashSet;
26 import java.util.logging.Logger;
29 * Monitors a directory for changes. The currernt implementation only checks
30 * files not directories and does not check for modifications in subdirectories.
32 * @author Erik Brakkee
34 public class DirectoryMonitor {
35 private static final Logger LOG = Logger.getLogger(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.fine("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;
114 * Listener interface to be provided by users of the directory monitor to
115 * get notified of changes.
117 * @author Erik Brakkee
119 public static interface Listener {
122 * File that has changed.
124 void fileChanged(File aFile);
128 * File that was created.
130 void fileCreated(File aFile);
134 * File that was deleted.
136 void fileDeleted(File aFile);