Monitor file changes with Java

Forword

I have not touched a similar problem before, so I wrote an article to record it.

Effect

File creation, deletion, and modification can be detected.

Process

I wrote a small demo, using the WatchService that is only available in java1.7 and above.

Code show as below

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
String logDir="/home/symeonchen/log_sample";
Path logPath = Paths.get(logDir);
for(;;){
try {
WatchService watcher = logPath.getFileSystem().newWatchService();
logPath.register(watcher, ENTRY_CREATE,ENTRY_DELETE, ENTRY_MODIFY);

WatchKey watckKey = watcher.take();

List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent<?> event : events) {
if (event.kind() == ENTRY_CREATE) {
// System.out.println("Created: " + event.context().toString());
}
if (event.kind() == ENTRY_DELETE) {
// System.out.println("Delete: " + event.context().toString());
}
if (event.kind() == ENTRY_MODIFY) {
System.out.println("Modify: " + event.context().toString());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
}
}

Document is here,which using Inotify. During the editing process, the generated temporary files will be recorded. Take sample.log as an example. During the process of saving and saving using Vim, .sample.log.swp, sample.log~, 4913, .sample.log will appear. Swx has so many temporary files, so it needs to be filtered if it is put into use.
In addition, RandomAccessFile is used to read the new part of the log, but because the filtering process has not been completed, the two modules work temporarily independently.