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.
17 package org.wamblee.io;
20 import java.io.FileFilter;
21 import java.util.ArrayList;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.List;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
31 * Monitors a directory for changes.
33 * @author Erik Brakkee
35 public class DirectoryMonitor {
37 private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
39 public static interface Listener {
40 void fileChanged(File aFile);
41 void fileCreated(File aFile);
42 void fileDeleted(File aFile);
45 private File _directory;
46 private FileFilter _filter;
47 private Listener _listener;
48 private Map<File,Date> _contents;
50 public DirectoryMonitor(File aDirectory, FileFilter aFilefilter, Listener aListener) {
51 _directory = aDirectory;
52 if ( !_directory.isDirectory()) {
53 throw new IllegalArgumentException("Directory '" + _directory + "' does not exist");
55 _filter = aFilefilter;
56 _listener = aListener;
57 _contents = new HashMap<File,Date>();
61 LOG.debug("Polling " + _directory);
62 Map<File,Date> newContents = new HashMap<File,Date>();
63 File[] files = _directory.listFiles(_filter);
64 for (File file: files) {
65 if ( _contents.containsKey(file)) {
66 Date oldDate = _contents.get(file);
67 if (file.lastModified() != oldDate.getTime()) {
68 _listener.fileChanged(file);
72 _contents.remove(file);
73 newContents.put(file, new Date(file.lastModified()));
75 _listener.fileCreated(file);
76 newContents.put(file, new Date(file.lastModified()));
79 for (File file: _contents.keySet()) {
80 _listener.fileDeleted(file);
82 _contents = newContents;