【问题标题】:Specify a file path that begins with the top-most directory指定以最顶层目录开头的文件路径
【发布时间】:2015-08-21 21:20:15
【问题描述】:

我正在打印以下行:

Files.exists(Paths.get("card/1.png"),java.nio.file.LinkOption.NOFOLLOW_LINKS);

使用Paths.get(...),我想在我的根目录中检索文件夹的路径开始,而不是在我当前的工作目录中。我依稀记得,但现在想不起来,从根开始文件检索的一些表达式。

表达式类似于~/,所以我可以写Paths.get(~/A/B);

如果不存在这样的表达式,那么在用户的最顶层文件夹开始检索的最佳替代方法是什么?

【问题讨论】:

  • 根目录的名称是什么?你怎么从你的终端去那里?
  • /Users/rohitkumar。我用cd ~/
  • 所以,这不是根目录。根目录是/。你想要的是你的 home 目录。 System.getProperty("user.home")
  • 是的,你有我。我想要我的主目录。

标签: java string file


【解决方案1】:

先找到你的主目录,然后使用带有相对路径的“resolve”:

Path homeDir = Path.get(System.getProperty("user.home"));
Path filePath = homeDir.resolve("card/1.png");

这里是JavaDoc of the resolve function。 relativize 函数在这种情况下也可能有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2010-12-12
    • 2012-08-28
    • 1970-01-01
    • 2021-04-15
    相关资源
    最近更新 更多