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 public class DirectoryMonitor {
35 private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
37 public static interface Listener {
38 void fileChanged(File aFile);
39 void fileCreated(File aFile);
40 void fileDeleted(File aFile);
43 private File _directory;
44 private FileFilter _filter;
45 private Listener _listener;
46 private Map<File,Date> _contents;
48 public DirectoryMonitor(File aDirectory, FileFilter aFilefilter, Listener aListener) {
49 _directory = aDirectory;
50 _filter = aFilefilter;
51 _listener = aListener;
52 _contents = new HashMap<File,Date>();
56 LOG.info("Polling " + _directory);
57 Map<File,Date> newContents = new HashMap<File,Date>();
58 File[] files = _directory.listFiles(_filter);
59 for (File file: files) {
60 if ( _contents.containsKey(file)) {
61 Date oldDate = _contents.get(file);
62 if (file.lastModified() != oldDate.getTime()) {
63 _listener.fileChanged(file);
67 _contents.remove(file);
68 newContents.put(file, new Date(file.lastModified()));
70 _listener.fileCreated(file);
71 newContents.put(file, new Date(file.lastModified()));
74 for (File file: _contents.keySet()) {
75 _listener.fileDeleted(file);
77 _contents = newContents;