web-dev-qa-db-ja.com

Javaのディレクトリリスナー

特定のディレクトリに加えられた変更をリッスンしたいアプリケーションがあります。そのディレクトリでファイルが追加、削除、または更新されるとすぐに、アプリケーションからpingが送信されます。

19
Jinith

JNotify を使用できます

JNotifyは、Javaライブラリーで、Javaアプリケーションが次のようなファイルシステムイベントをリッスンできるようにします。

Windows(2000以降)WindowsノートINofityをサポートするLinux(2.6.14以降)LinuxノートMac OS X(10.5以降)Mac OSノート

詳細:

JNotifyを こちら からダウンロードします

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
22
Jigar Joshi

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);
        }
23
rene

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);    }  
        }
3
Some Java Guy