Is there a way to get user's UID on Linux machine using java?

kofucii picture kofucii · Jan 25, 2011 · Viewed 17.7k times · Source

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.

Answer

jmj picture jmj · Jan 25, 2011

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) {
}

source