I tried this on mac:
touch ~/a.txt
And then java file:
import java.io.File;
public class testPwd {
public static void main(String [] args) {
File f = new File("~/a.txt");
System.out.println(f.exists());
}
}
It prints out "false".
Why is this? Does java recognize the "~" symbol? If I use absolute path, this f.exists() returns true.
Any explanations?
Why is this?
Because the ~
symbol is only understood by the Unix shell (and, confusingly, it was used in HTTP servers). Even if you wrote the program in C, it wouldn't understand ~
to designate the home directory of the current user.
To get the user's home directory, use System.getProperty("user.home")
. (Answer from What is the best way to find the users home directory in Java?)