34

I was wondering if using:

System.getProperty("user.dir"); 

to get the absolute path of a folder is the best way to go about it? I am looking to pass my application onto other computers and I need a full proof way of getting the 'home' directory so that I can just add onto the path when I need to use other folders by just doing:

String path = System.getProperty("user.dir"); String otherFolder = path + "\\other"; 
6
  • The root folder is "/". What are you trying to do? Commented Jul 12, 2014 at 4:50
  • "user.dir" is the current working directory, not the home directory Commented Jul 12, 2014 at 4:52
  • 1
    You seem to be mixing concepts here. user.dir is the current directory. The "absolute path" of a File object is obtained by getAbsolutePath(). Commented Jul 12, 2014 at 4:54
  • 1
    Once your title is fixed to express what you're really asking, the question becomes nonsensical. System.getProperty("user.dir") is not way to get the home directory at all, it is the way to get the current working directory. -1 for causing yourself confusion. Commented Jul 12, 2014 at 5:10
  • Sorry, not what I meant I guess. Just meant the working directory. Wrong choice of words :S Commented Jul 12, 2014 at 5:16

3 Answers 3

58

way of getting home directory of current user is

String currentUsersHomeDir = System.getProperty("user.home"); 

and to append path separator

String otherFolder = currentUsersHomeDir + File.separator + "other"; 

File.separator

The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.

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

3 Comments

It's "fool-proof", not "full proof"; and no I did not downvote.
See "JDK-4787931 : System property "user.home" does not correspond to "USERPROFILE" (win)" mentioned in stackoverflow.com/questions/585534/…
it has been resolved already @Jay
8

"user.dir" is the current working directory, not the home directory It is all described here.

http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Also, by using \\ instead of File.separator, you will lose portability with *nix system which uses / for file separator.

2 Comments

Use File.separator for best cross platform or '/'. The '/' works in Java even on Windows.
Thanks for the tip. I never knew that '/' also works in Windows.
7

Program to get the current working directory=user.dir

public class CurrentDirectoryExample { public static void main(String args[]) { String current = System.getProperty("user.dir"); System.out.println("Current working directory in Java : " + current); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.