1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WatchServiceで特定のファイルを監視したい

Posted at

たとえばdir\file.txtが変更されたことをWatchServiceで検出したい場合、次のようなコードを書きたくなりますが、これは実行時例外(NotDirectoryException)が発生します。

var file = Paths.get("dir", "file.txt");
var watcher = FileSystems.getDefault().newWatchService();
file.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);

Path::registerのJavaDocにもある通り、WatchServiceの登録対象はディレクトリです。あるいはWatchServiceは登録したディレクトリの配下にあるファイルやディレクトリに発生したイベントを監視している、と言い換えてもいいでしょう。よって特定のファイルのイベントだけを検出したい場合は、たとえば次のような工夫が必要になります。

var file = Paths.get("dir", "file.txt");
var directory = file.getParent();
var watcher = FileSystems.getDefault().newWatchService();
directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);

// 割り込みなどで中断するまで、file.txtを監視し続ける。
while (true) {
    var watchKey = watcher.take();
    for (var event : watchKey.pollEvents()) {
        var modified = (Path) event.context();
        if (modified.equals(file.getFileName())) {
            // Do Something
        }
    }
}

WatchEvent::contextでイベントが発生したエントリの情報を取得できます。WatchEvent::contextの戻り値はObjectですが、実態としてはPathオブジェクトが返ってくるので、上記の例ではキャストして、変数modifiedとしています。

またmodifiedに格納されたPathオブジェクトは、WatchServiceに登録されたディレクトリからの相対パスになっています。要するにvar modified = Paths.get("file.txt");となっているため、equalsなどで比較する場合は注意する必要があります。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?