0

I am executing a java program as a .jar file on RPI, in which it is critical to receive the right home path of the user "pi".

System.getProperty("user.home")

returns me /root, what is the wrong directory and messes up my file structure since in that dir. I am creating further folders etc. I am starting the program as user pi.

How can I receive the right homefolder for a certain user (in my case pi, "/home/pi/") without hacking?

PS: That user could be entered as an argument ofcourse.

Raspbian stretch
openjdk 11.0.3 2019-04-16
OpenJDK Runtime Environment (build 11.0.3+1-Raspbian-1)
OpenJDK Server VM (build 11.0.3+1-Raspbian-1, mixed mode)

1 Answer 1

2

There is no clean (portable) way to find information about another user in Java.

If you are OK with an operating system specific solution (for a Linux-based system), you can use Process and friends to run the getent passwd external command, then read and parse its output.

The getent passwd output consists of one line per matched user. Each line consists of a number of colon separated fields, so you could parse the lines using String::split. On my system, the user's home directory is the 6th field in the entry.

For more information, read man getent and the javadocs for Process and ProcessBuilder.

3
  • Hm not very sufficent, a pity. Then I'd rather go with try{ for the /home/$user path.
    – pikkuez
    Jul 20, 2019 at 13:48
  • 2
    That won't work. The user's home directory is not necessarily in "/home". Trust me you can't use a heuristic. You need to consult the sources of information that getent is looking at ... and it could be different places; e.g. /etc/passwd, LDAP, etc.
    – Stephen C
    Jul 20, 2019 at 14:17
  • Sounds reasonable.
    – pikkuez
    Jul 20, 2019 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.