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 ?

6
  • 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 Commented Feb 27, 2015 at 11:13
  • possible duplicate of How to get the User ~/Library path in Java for the Mac OS Commented Feb 27, 2015 at 11:17
  • possible duplicate of What is the best way to find the users home directory in Java? Commented Feb 27, 2015 at 11:18
  • How nice would it be if people checked if a question and answer already existed before posting anything.. Commented Feb 27, 2015 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. Commented Feb 27, 2015 at 11:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

user.home does the trick. Thanks, I need 8min to accept your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.