java - WatchService - incorrectly resolved absolute path -


i've been playing around java.nio.file.watchservice , noticed paths returned watchevent.context() not return correct .toabsolutepath(). here example application:

public class fswatcher {   public static void main(string[] args) throws ioexception, interruptedexception {     if (args.length != 1) {       system.err.println("invalid number of arguments: " + args.length);       return;     }     //run application absolute path /home/<username>     final path watcheddirectory = paths.get(args[0]).toabsolutepath();     final filesystem filesystem = filesystems.getdefault();     final watchservice watchservice = filesystem.newwatchservice();     watcheddirectory.register(watchservice, standardwatcheventkinds.entry_create);      while (true) {       watchkey watchkey = watchservice.take();       (watchevent<?> watchevent : watchkey.pollevents()) {         if (watchevent.kind().equals(standardwatcheventkinds.overflow)) {           continue;         }          final path createdfile = (path) watchevent.context();         final path expectedabsolutepath = watcheddirectory.resolve(createdfile);         system.out.println("context path: " + createdfile);         system.out.println("context absolute path: " + createdfile.toabsolutepath());         system.out.println("expected absolute path: " + expectedabsolutepath);         system.out.println("usr.dir: " + system.getproperty("user.dir"));       }       watchkey.reset();     }   } } 

example output:

context path: document.txt context absolute path: /home/svetlin/workspaces/default/fswatcher/document.txt expected absolute path: /home/svetlin/document.txt usr.dir: /home/svetlin/workspaces/default/fswatcher 

it seems absolute path resolved against user.dir system property instead of path used watchservice registration. that's problem because when try use (for instance files.copy()) path returned watchevent receive java.nio.file.nosuchfileexception, expected there no such file @ path. missing or bug in jre ?

this not bug, confusing.

if watchevent.context() returns path relative:

in case of entry_create, entry_delete, , entry_modify events context path relative path between directory registered watch service, , entry created, deleted, or modified.

now if turn such path absolute path calling toabsolutepath() happens not relative watched directory default directory.

this method resolves path in implementation dependent manner, typically resolving path against file system default directory. depending on implementation, method may throw i/o error if file system not accessible.

therefore turn path absolute path need use

watcheddirectory.resolve(createdfile); 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -