Java 中的目录监听器

发布于 2024-10-16 10:08:33 字数 77 浏览 3 评论 0原文

我有一个应用程序,我想在其中监听对特定目录所做的任何更改。一旦该目录中添加、删除或更新了任何文件,应用程序应该立即对我进行 ping 操作。

I have an application in which I want to listen to any changes made to a particular directory. The application should ping me as soon as there are any files added, deleted or updated in that directory.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

℉服软 2024-10-23 10:08:33

从 Java 1.7 开始,您可以使用 Watch Service API 来注册对于目录事件。它是 Java 新 I/O (NIO) 的一部分图书馆,不需要任何额外的资源。如何使用 API 的示例可以在官方文档中找到。

注册 WatchService 后,您可以检索目标路径的事件,如下所示:

for (WatchEvent<?> event: key.pollEvents()) {
             // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);

            // print out event
            System.out.format("%s: %s\n", event.kind().name(), child);
        }

Since Java 1.7 you can use the Watch Service API to register for directory events. It is part of Java's New I/O (NIO) library and does not require any additional resources. An example how to use the API can be found in the official documentation.

After registering the WatchService you can retrieve events for the target path like this:

for (WatchEvent<?> event: key.pollEvents()) {
             // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);

            // print out event
            System.out.format("%s: %s\n", event.kind().name(), child);
        }
柳絮泡泡 2024-10-23 10:08:33

您可以使用 JNotify

JNotify是一个java库,允许java应用程序监听文件
系统事件,例如: 文件已创建
文件已修改 文件已重命名 文件
已删除支持的平台

Windows(2000 或更高版本)Windows 注释
支持 INofity 的 Linux(2.6.14 或
较新版本)Linux 注释 Mac OS X(10.5 或
较新)Mac OS 注释

更多信息:

此处

解压 zip,根据平台将 .dll/.so 放入您的 lib 路径中。并在类路径中创建一个提供jnotify-0.93.jar的类。

示例代码:

package org.life.java.stackoverflow.questions;

import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyListener;

/**
 *
 * @author Jigar
 */
public class JNotifyDemo {

    public void sample() throws Exception {
        // path to watch
        String path = System.getProperty("user.home");

        // watch mask, specify events you care about,
        // or JNotify.FILE_ANY for all events.
        int mask = JNotify.FILE_CREATED
                | JNotify.FILE_DELETED
                | JNotify.FILE_MODIFIED
                | JNotify.FILE_RENAMED;

        // watch subtree?
        boolean watchSubtree = true;

        // add actual watch
        int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());

        // sleep a little, the application will exit if you
        // don't (watching is asynchronous), depending on your
        // application, this may not be required
        Thread.sleep(1000000);

        // to remove watch the watch
        boolean res = JNotify.removeWatch(watchID);
        if (!res) {
            // invalid watch ID specified.
        }
    }

    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) throws Exception {
        new JNotifyDemo().sample();
    }
}

输出:

modified C:\Documents and Settings\jigar: LOCALS~1\Temp\etilqs_4s8ywsvyukghK0uDxRop
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_4s8ywsvyukghK0uDxRop
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\output1295531079119
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default
deleted C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001ea9
created C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\output1295531079119
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Current Session
deleted C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001ea8
created C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf

You can use JNotify

JNotify is a java library that allow java application to listen to file
system events, such as: File created
File modified File renamed File
deleted Supported platforms

Windows (2000 or newer) Windows notes
Linux with INofity support (2.6.14 or
newer) Linux notes Mac OS X (10.5 or
newer) Mac OS notes

More Info :

Download JNotify from here

Extract the zip, put .dll/.so according to platform in your lib path. and create a class provide jnotify-0.93.jar in class path.

Sample code:

package org.life.java.stackoverflow.questions;

import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyListener;

/**
 *
 * @author Jigar
 */
public class JNotifyDemo {

    public void sample() throws Exception {
        // path to watch
        String path = System.getProperty("user.home");

        // watch mask, specify events you care about,
        // or JNotify.FILE_ANY for all events.
        int mask = JNotify.FILE_CREATED
                | JNotify.FILE_DELETED
                | JNotify.FILE_MODIFIED
                | JNotify.FILE_RENAMED;

        // watch subtree?
        boolean watchSubtree = true;

        // add actual watch
        int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());

        // sleep a little, the application will exit if you
        // don't (watching is asynchronous), depending on your
        // application, this may not be required
        Thread.sleep(1000000);

        // to remove watch the watch
        boolean res = JNotify.removeWatch(watchID);
        if (!res) {
            // invalid watch ID specified.
        }
    }

    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) throws Exception {
        new JNotifyDemo().sample();
    }
}

Output:

modified C:\Documents and Settings\jigar: LOCALS~1\Temp\etilqs_4s8ywsvyukghK0uDxRop
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_4s8ywsvyukghK0uDxRop
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\output1295531079119
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default
deleted C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001ea9
created C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\output1295531079119
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Current Session
deleted C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001ea8
created C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf
modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf
最笨的告白 2024-10-23 10:08:33

java中的Jnotify用于文件通知。代码示例

   public void sample() throws Exception {
        // path to watch    
        String path = System.getProperty("user.home");    
        // watch mask, specify events you care about,    
        // or JNotify.FILE_ANY for all events.    
        int mask = JNotify.FILE_CREATED  |                
        JNotify.FILE_DELETED  |                
        JNotify.FILE_MODIFIED |                
        JNotify.FILE_RENAMED;    
        // watch subtree?    boolean watchSubtree = true;    
        // add actual watch    
        int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());    
        // sleep a little, the application will exit if you    
        // don't (watching is asynchronous), depending on your    
        // application, this may not be required    
        Thread.sleep(1000000);    
        // to remove watch the watch    
        boolean res = JNotify.removeWatch(watchID);    
        if (!res) {      
            // invalid watch ID specified.    
            }  
        }  
    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);    }  
        }

Jnotify for file notification in java. Code sample

   public void sample() throws Exception {
        // path to watch    
        String path = System.getProperty("user.home");    
        // watch mask, specify events you care about,    
        // or JNotify.FILE_ANY for all events.    
        int mask = JNotify.FILE_CREATED  |                
        JNotify.FILE_DELETED  |                
        JNotify.FILE_MODIFIED |                
        JNotify.FILE_RENAMED;    
        // watch subtree?    boolean watchSubtree = true;    
        // add actual watch    
        int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());    
        // sleep a little, the application will exit if you    
        // don't (watching is asynchronous), depending on your    
        // application, this may not be required    
        Thread.sleep(1000000);    
        // to remove watch the watch    
        boolean res = JNotify.removeWatch(watchID);    
        if (!res) {      
            // invalid watch ID specified.    
            }  
        }  
    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);    }  
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文