How to detect file system in java

I would like to know how to effectively implement file system changes in java? Say I got a file in a folder and changed that file. I would like to be notified of this change in java as soon as possible (often not polling if possible).

Because I think in a few seconds I could call java.io.file.lastModified , but I don’t like the sound of this solution at all.

alfred@alfred-laptop :~/testje$ java -version java version "1.6.0_18" Java(TM) SE Runtime Environment (build 1.6.0_18-b07) Java HotSpot(TM) Server VM (build 16.0-b13, mixed mode) 
+4
source share
4 answers

Check out JNotify , which performs this type of monitoring.

Java 7 will have a few more advanced APIs ( WatchService ) for this kind of work, which will eliminate polling in operating systems that support this.

+8
source

I doubt there is a pure java way for this. Operating systems offer an API for monitoring file system activity. You may have to call these APIs.

+1
source

Use JNotify. All you have to do is add jnotify.jar to the build path and put two dll files ie jnotify.dll jnotify_64bit.dll and inside lib jdk. Demo program

 package jnotify; import net.contentobjects.jnotify.JNotify; import net.contentobjects.jnotify.JNotifyListener; public class MyJNotify { public void sample() throws Exception { String path = "Any Folder location here which you want to monitor"; System.out.println(path); int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED; boolean watchSubtree = true; int watchID = JNotify .addWatch(path, mask, watchSubtree, new Listener()); Thread.sleep(1000000); boolean res = JNotify.removeWatch(watchID); if (!res) { System.out.println("Invalid"); } } class Listener implements JNotifyListener { public void fileRenamed(int wd, String rootPath, String oldName, String newName) { print("renamed " + rootPath + " : " + oldName + " -> " + newName); } public void fileModified(int wd, String rootPath, String name) { print("modified " + rootPath + " : " + name); } public void fileDeleted(int wd, String rootPath, String name) { print("deleted " + rootPath + " : " + name); } public void fileCreated(int wd, String rootPath, String name) { print("created " + rootPath + " : " + name); } void print(String msg) { System.err.println(msg); } } public static void main(String[] args) { try { new MyJNotify().sample(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 
+1
source

There is an Apache package that monitors the file system: commons.io.monitor.

Documentation

Example

From what I can say, you still need to interrogate, although you have control over the frequency.

+1
source

Source: https://habr.com/ru/post/1304208/


All Articles