Search code examples
javapathclasspathniowatchservice

Get the absolute path of a file on the class path


Setup

  • Pasted is modified version of an Oracle example
  • While the program's running, if you now make a new file or directory directory inside of the path directory, you'll see that the path displayed is incorrect
  • For example, when I run it, it shows the absolute path of a newly-created file in the path directory as /home/hoagy/test/new_file, when the actual path to the file is /home/hoagy/test/path/new_file

Question

  • How do I get the proper absolute path?

Code

package path.question;

import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;

public class WatchDir {

    private final WatchService watcher;
    private final Map<WatchKey,Path> keys;

    @SuppressWarnings("unchecked")
    static <T> WatchEvent<T> cast(WatchEvent<?> event) {
        return (WatchEvent<T>)event;
    }

    private void register(Path dir) throws IOException {
        WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        keys.put(key, dir);
    }

    WatchDir(Path dir) throws IOException {
        this.watcher = FileSystems.getDefault().newWatchService();
        this.keys = new HashMap<WatchKey,Path>();
        register(dir);
    }

    void processEvents() {
        for (;;) {

            WatchKey key;
            try { key = watcher.take(); }
            catch (InterruptedException x) { return; }

            Path dir = keys.get(key);
            if (dir == null) {
                continue;
            }

            for (WatchEvent<?> event: key.pollEvents()) {
                WatchEvent.Kind kind = event.kind();

                if (kind == OVERFLOW) { continue; }

                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = dir.resolve(name);

                System.out.println("Full path: " + name.toAbsolutePath().toString());
            }

            key.reset();
        }
    }

    public static void main(String[] args) throws IOException {
        Path dir = Paths.get("./path");
        new WatchDir(dir).processEvents();
    }
}

Solution

  • Replace :

     //prints the "absolute path" of the name of the file 
     System.out.println("Full path: " + name.toAbsolutePath().toString());
    

    With

     //prints the "absolute path" of the "child" 
     System.out.println("child " + child.toAbsolutePath().toString());