-1

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?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Hind Forsum
  • 9,717
  • 13
  • 63
  • 119
  • 3
    `Does java recognize the "~" symbol?` — As you have demonstrated, it does not. What else are you asking? – khelwood Oct 31 '18 at 13:23
  • That's a Unix convention; not sure if it's platform independent. – duffymo Oct 31 '18 at 13:26
  • 1
    Yeah, you can't do that. Use `System.getProperty("user.home");` as demonstrated in this question https://stackoverflow.com/questions/585534/what-is-the-best-way-to-find-the-users-home-directory-in-java to get the user's home directory. – Frzn Flms Oct 31 '18 at 13:26

1 Answers1

4

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?)

SeverityOne
  • 2,476
  • 12
  • 25