Java model 7 added characteristic to look at File System or Moniter Folder and provides an alert if any modifications made into folders just like the creation of file , modification of file and deletion of recordsdata.
The watch service API launched in java 7 NIO.2 JSR 203 as thread secure service ,which is able to watching any object for modifications and pushes again these modifications for you as occasion notifications. Watched objects ought to implement java.nio.file.Watchable interface which is the important thing interface on this API. All of the API lessons reside within the java.nio.file package deal.
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
|
package deal com.techzoo.monitor;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
public class MonitorFiles {
public static void most important(String[] args) throws IOException{
Path demoFolder = Paths.get(“./demo/”);
WatchService watchService = FileSystems.getDefault().newWatchService();
demoFolder.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
boolean flag = true;
do{
WatchKey watchKey;
strive {
watchKey= watchService.take();
}
catch (InterruptedException x) {
return;
}
for (WatchEvent occasion : watchKey.pollEvents()) {
WatchEvent.Sort type = occasion.type();
if (StandardWatchEventKinds.ENTRY_CREATE.equals(occasion.type())) {
String fileName = occasion.context().toString();
System.out.println(“File Created:” + fileName);
}
if (StandardWatchEventKinds.ENTRY_DELETE.equals(occasion.type())) {
String fileName = occasion.context().toString();
System.out.println(“File Deleted:” + fileName);
}
if (StandardWatchEventKinds.ENTRY_MODIFY.equals(occasion.type())) {
String fileName = occasion.context().toString();
System.out.println(“File Modified:” + fileName);
}
}
flag = watchKey.reset();
} whereas(flag);
}
}
|
Output of above program will look much like…
Supply techzoo.org