【问题标题】:java.io.File cannot recognize "~" symbol of home dir?java.io.File 无法识别主目录的“~”符号?
【发布时间】:2019-04-04 16:19:31
【问题描述】:

我在 mac 上试过这个:

touch ~/a.txt

然后是java文件:

import java.io.File;

public class testPwd {
    public static void main(String [] args) {
        File f = new File("~/a.txt");
        System.out.println(f.exists());
    }
}

它打印出“假”。

这是为什么? java能识别“~”符号吗?如果我使用绝对路径,这个 f.exists() 返回 true。

有什么解释吗?

【问题讨论】:

  • Does java recognize the "~" symbol? — 正如您所展示的,事实并非如此。你还问什么?
  • 这是 Unix 约定;不确定它是否独立于平台。
  • 是的,你不能那样做。使用System.getProperty("user.home");,如本问题stackoverflow.com/questions/585534/… 所示,获取用户的主目录。

标签: java file io directory


【解决方案1】:

这是为什么?

因为~ 符号只能被 Unix shell 理解(而且令人困惑的是,它被用于 HTTP 服务器)。即使你用 C 编写程序,它也无法理解 ~ 指定当前用户的主目录。

要获取用户的主目录,请使用System.getProperty("user.home")。 (来自What is the best way to find the users home directory in Java?的回答)

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 2023-02-02
    • 2015-01-13
    • 2023-03-14
    相关资源
    最近更新 更多