【问题标题】:Get the absolute path of a file on the class path获取类路径上文件的绝对路径
【发布时间】:2016-11-19 11:29:09
【问题描述】:

设置

  • 粘贴的是 Oracle example 的修改版本
  • 在程序运行时,如果您现在在path 目录中创建一个新文件或目录目录,您会看到显示的路径不正确
  • 比如我运行它时,在path目录下新建文件的绝对路径显示为/home/hoagy/test/new_file,而文件的实际路径为/home/hoagy/test/path/new_file

问题

  • 如何获得正确的绝对路径?

代码

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();
    }
}

【问题讨论】:

  • A minimal reproducible example 会比这个包含许多问题不需要的代码行的长类更好。让帮助变得更容易。
  • 好电话。按建议编辑。

标签: java path classpath nio watchservice


【解决方案1】:

替换:

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

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

【讨论】:

  • @Hoagy Carmichael 感谢您的编辑。帖子回答了你的问题吗?
猜你喜欢
  • 1970-01-01
  • 2012-04-24
  • 2011-12-29
  • 2021-10-18
  • 1970-01-01
  • 2010-09-18
  • 2023-04-05
相关资源
最近更新 更多