Get the first and last name of the current Windows user?

I know that you can get the username with something like System.getProperty("user.name") , but I'm looking for a way to get the name and surname of the current user.

Is there a built-in Java library that does this? Or do you need to connect to the Windows API? Or maybe you need to pull it out of Active Directory? It looks relatively easy with .NET , but I cannot find a way to do this in Java.

+6
source share
2 answers

As suggested by Brian Roach in the comments, it's pretty easy to do this with JNA, as it has a built-in shell for Secur32 that wraps the GetUsernameEx () function (which ultimately is a system call wrapped in the .NET library you linked above).

Usage will be something like this:

 import com.sun.jna.ptr.IntByReference; import com.sun.jna.platform.win32.Secur32; // ... char[] name = new char[100]; // or whatever is appropriate Secur32.INSTANCE.GetUserNameEx( Secur32.EXTENDED_NAME_FORMAT.NameDisplay, name, new IntByReference(name.length) ); String fullName = new String(name).trim(); 

Note that this will give you the full name in the same format as typing net user %USERNAME% /domain on the command line.

+5
source

Or simply,

 String fullName = Secur32Util.getUserNameEx(Secur32.EXTENDED_NAME_FORMAT.NameDisplay); 

But this is the same as the top answer

+1
source

Source: https://habr.com/ru/post/908167/


All Articles