I am not sure if this is a bug or if I am doing it wrong.
import java.io.*;
import java.nio.file.*;
import java.util.*;
void foo ()
{
String dir = "/tmp/mytest";
// lets watch in dir for new files
WatchService ws = FileSystems.getDefault ().newWatchService ();
Path p = Paths.get (dir);
p.register (ws, StandardWatchEventKinds.ENTRY_CREATE);
for (int i = 0; i < 8; i ++) // just to have a timeline in the output to show
{
System.out.println ("check " + i);
WatchKey wk = ws.poll ();
if (wk != null)
{
for (WatchEvent <?> we : wk.pollEvents ())
{
Path pc = (Path) we.context ();
System.out.println (" fn=" + pc.getFileName () + " ap=" + pc.toAbsolutePath ());
}
}
// simulate a creation - its the same if I do it manually on the console
if (i == 3) // create a file in the dir that is watched
{
File f = new File (dir + "/a.txt");
f.createNewFile ();
System.out.println ("created " + f.getAbsolutePath ());
}
Thread.sleep (1000);
}
}
}
Output
dir=/tmp/mytest
check 0
check 1
check 2
check 3
created /tmp/mytest/a.txt
check 4
fn=a.txt ap=/data/myprojects/test1/a.txt
check 5
check 6
check 7
Why do the absolute Paths between creation and watcher not match? Why is the absolute Path of the WatchEvent the programs path and not the path of the real file?
I am unsing OpenJdk11 on a Debian Linux 10.