Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a user's home directory on linux or unix?

Normally you use the statement

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

to get the home directory of the user on any platform. See the method documentation for getProperty to see what else you can get.

There may be access problems you might want to avoid by using this workaround (Using a security policy file)


For UNIX-Like systems you might want to execute "echo ~username" using the shell (so use Runtime.exec() to run {"/bin/sh", "-c", "echo ~username"}).


Try this on Java:

System.out.println("OS: " + System.getProperty("os.name") + ", USER DIRECTORY: " + System.getProperty("user.home"));

For an arbitrary user, as the webserver:

private String getUserHome(String userName) throws IOException{
    return new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(new String[]{"sh", "-c", "echo ~" + userName}).getInputStream())).readLine();
}

You can use the environment variable $HOME for that.


If you want to find a specific user's home directory, I don't believe you can do it directly.

When I've needed to do this before from Java I had to write some JNI native code that wrapped the UNIX getpwXXX() family of calls.