Is there a way to get user's UID on Linux machine using java? I'm aware of System.getProperty("user.name");
method, but it return's user name and I'm looking for UID.
Asked
Active
Viewed 1.8k times
13
Paul Rubel
- 24,802
- 7
- 54
- 76
kofucii
- 6,579
- 12
- 47
- 77
5 Answers
13
you can execute id
command and read result.
for example:
$ id -u jigar
output:
1000
you can execute command by
try {
String userName = System.getProperty("user.name");
String command = "id -u "+userName;
Process child = Runtime.getRuntime().exec(command);
// Get the input stream and read from it
InputStream in = child.getInputStream();
int c;
while ((c = in.read()) != -1) {
process((char)c);
}
in.close();
} catch (IOException e) {
}
jmj
- 225,392
- 41
- 383
- 426
-
It would be much easier to parse if you executed "id -n" – Bill Lynch Jan 25 '11 at 16:42
-
1`id -u
` will only print the UID. – dogbane Jan 25 '11 at 16:44 -
The OP already has the username from `System.getProperty("user.name")`. – dogbane Jan 25 '11 at 16:48
-
@Anto there are lots of possibility to play with it – jmj Jan 25 '11 at 17:11
5
If you can influence how the Java VM is started, you could handover the uid as a user property:
java -Duserid=$(id -u) CoolApp
In your CoolApp, you could simply fetch the ID with:
System.getProperty("userid");
Regards,
Martin.
4
There is actually an api for this. There is no need to call a shell command or use JNI, just
def uid = new com.sun.security.auth.module.UnixSystem().getUid()
Erik Martino
- 3,561
- 1
- 15
- 11
1
Just open the /etc/passwd
file and search for the line that has a user equal to System.getProperty("user.name")
.
vz0
- 30,291
- 7
- 37
- 74
-
1that does not work on systems using other methods for keeping the user database e.g. [NIS](http://en.wikipedia.org/wiki/Network_Information_Service) or [LDAP](http://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol) etc. (typically used on clusters) – Andre Holzner Jul 17 '13 at 13:23