Tuesday, November 13, 2012

JDK7 vs. JDK 6 File Monitoring

One of the really nice advancements, or features of Java 7 is the WatchService. This feature takes advantage of the OS file event notification facilities where available, or otherwise uses a "primitive" polling mechanism. In my blog article WatchService Using ScheduledExecutorService Example, I show an example of how to use the WatchService along with an ExecutorService to do file monitoring. This is really easy to implement and use.

However, the question of how to do it on JDK 6 was posed to me for those who can't do an upgrade for business reasons. I did a quick Google search to see what was out there. Alas, some of the most popular search results were poor, or really badly implemented solutions. I did come across a nice piece of code done by Pascal Essiembre. I didn't find much more on the developer. I would give a link to his work if I were sure that what I found was him. Pascal wrote the code below which is EPL 1.0 so you are free to use it. I used it to check it out, and it works likely in the same manner as the "primitive" implementation in JDK7. Here is the code unmodified from the form I found. This is very nicely done. Good code lives on. I just wish this were more near the top of the search results.

Thanks Pascal for your code contribution to the Java community.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/*******************************************************************************
 * Copyright (c) 2007 Pascal Essiembre.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 *
 * Contributors:
 *    Pascal Essiembre - initial API and implementation
 ******************************************************************************/
 
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;
 
/**
 * Class monitoring a {@link File} for changes.
 *
 * @author Pascal Essiembre
 */
public class FileMonitor {
 
  private static final FileMonitor instance = new FileMonitor();
 
  private Timer timer;
 
  private Hashtable<String, FileMonitorTask> timerEntries;
 
  /**
   * Gets the file monitor instance.
   *
   * @return file monitor instance
   */
  public static FileMonitor getInstance() {
    return instance;
  }
 
  /**
   * Constructor.
   */
  private FileMonitor() {
    // Create timer, run timer thread as daemon.
    timer = new Timer(true);
    timerEntries = new Hashtable<String, FileMonitorTask>();
  }
 
  /**
   * Adds a monitored file with a {@link FileChangeListener}.
   *
   * @param listener
   *          listener to notify when the file changed.
   * @param fileName
   *          name of the file to monitor.
   * @param period
   *          polling period in milliseconds.
   */
  public void addFileChangeListener(FileChangeListener listener, String fileName, long period)
      throws FileNotFoundException {
    addFileChangeListener(listener, new File(fileName), period);
  }
 
  /**
   * Adds a monitored file with a FileChangeListener.
   *
   * @param listener
   *          listener to notify when the file changed.
   * @param fileName
   *          name of the file to monitor.
   * @param period
   *          polling period in milliseconds.
   */
  public void addFileChangeListener(FileChangeListener listener, File file, long period)
      throws FileNotFoundException {
    removeFileChangeListener(listener, file);
    FileMonitorTask task = new FileMonitorTask(listener, file);
    timerEntries.put(file.toString() + listener.hashCode(), task);
    timer.schedule(task, period, period);
  }
 
  /**
   * Remove the listener from the notification list.
   *
   * @param listener
   *          the listener to be removed.
   */
  public void removeFileChangeListener(FileChangeListener listener, String fileName) {
    removeFileChangeListener(listener, new File(fileName));
  }
 
  /**
   * Remove the listener from the notification list.
   *
   * @param listener
   *          the listener to be removed.
   */
  public void removeFileChangeListener(FileChangeListener listener, File file) {
    FileMonitorTask task = timerEntries.remove(file.toString() + listener.hashCode());
    if (task != null) {
      task.cancel();
    }
  }
 
  /**
   * Fires notification that a file changed.
   *
   * @param listener
   *          file change listener
   * @param file
   *          the file that changed
   */
  protected void fireFileChangeEvent(FileChangeListener listener, File file) {
    listener.fileChanged(file);
  }
 
  /**
   * File monitoring task.
   */
  class FileMonitorTask extends TimerTask {
    FileChangeListener listener;
 
    File monitoredFile;
 
    long lastModified;
 
    public FileMonitorTask(FileChangeListener listener, File file) throws FileNotFoundException {
      this.listener = listener;
      this.lastModified = 0;
      monitoredFile = file;
      if (!monitoredFile.exists()) { // but is it on CLASSPATH?
        URL fileURL = listener.getClass().getClassLoader().getResource(file.toString());
        if (fileURL != null) {
          monitoredFile = new File(fileURL.getFile());
        } else {
          throw new FileNotFoundException("File Not Found: " + file);
        }
      }
      this.lastModified = monitoredFile.lastModified();
    }
 
    public void run() {
      long lastModified = monitoredFile.lastModified();
      if (lastModified != this.lastModified) {
        this.lastModified = lastModified;
        fireFileChangeEvent(this.listener, monitoredFile);
      }
    }
  }
}
 
/*******************************************************************************
 * Copyright (c) 2007 Pascal Essiembre. All rights reserved. This program and
 * the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 *
 * Contributors: Pascal Essiembre - initial API and implementation
 ******************************************************************************/
 
/**
 * Listener interested in {@link File} changes.
 *
 * @author Pascal Essiembre
 */
interface FileChangeListener {
  /**
   * Invoked when a file changes.
   *
   * @param fileName
   *          name of changed file.
   */
  public void fileChanged(File file);
}

0 comments :

Popular Posts