Detect if Java application was run as a Windows admin Detect if Java application was run as a Windows admin windows windows

Detect if Java application was run as a Windows admin


I've found a different solution that seems to be platform-independent. It tries to write system-preferences. If that fails, the user might not be an admin.

As Tomáš Zato suggested, you might want to suppress error messages caused by this method. You can do this by setting System.err:

import java.io.OutputStream;import java.io.PrintStream;import java.util.prefs.Preferences;import static java.lang.System.setErr;import static java.util.prefs.Preferences.systemRoot;public class AdministratorChecker{    public static final boolean IS_RUNNING_AS_ADMINISTRATOR;    static    {        IS_RUNNING_AS_ADMINISTRATOR = isRunningAsAdministrator();    }    private static boolean isRunningAsAdministrator()    {        Preferences preferences = systemRoot();        synchronized (System.err)        {            setErr(new PrintStream(new OutputStream()            {                @Override                public void write(int b)                {                }            }));            try            {                preferences.put("foo", "bar"); // SecurityException on Windows                preferences.remove("foo");                preferences.flush(); // BackingStoreException on Linux                return true;            } catch (Exception exception)            {                return false;            } finally            {                setErr(System.err);            }        }    }}


I found this code snippet online, that I think will do the job for you.

public static boolean isAdmin() {    String groups[] = (new com.sun.security.auth.module.NTSystem()).getGroupIDs();    for (String group : groups) {        if (group.equals("S-1-5-32-544"))            return true;    }    return false;}

It ONLY works on windows, and comes built in to the core Java package. I just tested this code and it does work. It surprised me, but it does.

The SID S-1-5-32-544 is the id of the Administrator group in the Windows operating system.

Here is the link for more details of how it works.


There is not such a facility available in the Java Runtime Environment, but might be in a platform-dependent native routine. Note that usually the best way to be certain is to actually try to do it, and see if it fails.