有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA木卫一。文件无法识别主目录的“~”符号?

我在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

有什么解释吗


共 (1) 个答案

  1. # 1 楼答案

    Why is this?

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

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