Search code examples
javalinuxuid

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


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.


Solution

  • 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