0

I am using MacBook. I have a file located under ~/temp/note.txt.

(~ represents home directory by default in terminal).

I want to access this file in my java code:

File fileDir = new File("~/temp");
// I get exist = false, why?
boolean exist = fileDir.exist();

But my java code can't find the directory ~/temp. I guess it is because java code can't recognize ~ ? How to make it work ?

Leem.fin
  • 40,781
  • 83
  • 202
  • 354
  • Try ./ instead of ~/ if you are running this program from the home directory. If you want the home directory, you need to give the path explicitly – Chetan Kinger Feb 27 '15 at 11:13
  • possible duplicate of [How to get the User ~/Library path in Java for the Mac OS](http://stackoverflow.com/questions/1095944/how-to-get-the-user-library-path-in-java-for-the-mac-os) – Chetan Kinger Feb 27 '15 at 11:17
  • possible duplicate of [What is the best way to find the users home directory in Java?](http://stackoverflow.com/questions/585534/what-is-the-best-way-to-find-the-users-home-directory-in-java) – Paco Abato Feb 27 '15 at 11:18
  • How nice would it be if people checked if a question and answer already existed before posting anything.. – Chetan Kinger Feb 27 '15 at 11:19
  • An information I am missing in the other answers: `~` is parsed by the shell. The issue that it doesn't work exists in all (other) programming languages. – glglgl Feb 27 '15 at 11:23
  • Do you have a folder called `~`? No? That's why. (`~` is only a shortcut to save typing in your shell, it's not what the directory is actually called) – user253751 Feb 27 '15 at 11:33

1 Answers1

4

May be you could use the system variables and concatenate with 'temp.txt'.
You could obtain your user home directory via :

 System.getProperty("user.home")

If it's not ok, try

System.getProperty("user.dir")

Hope this could help

vincent
  • 1,214
  • 12
  • 22