I know you can retrieve the username with something like System.getProperty("user.name")
but I am looking for a way to retrieve the first and last name of the current user.
Is there a native Java library that does this? Or do you have to plug into the Windows API? Or maybe you have to pull it from Active Directory? This seems relatively easy with .NET but I can't find a way to do it in Java.
As Brian Roach suggested in the comments, it's pretty straight-forward to do this with JNA, since it has a built-in wrapper for Secur32 which wraps the GetUsernameEx() function (which is ultimately the system call wrapped by the .NET library you linked to above).
Use would 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 you'd get typing net user %USERNAME% /domain
at the command prompt.
Or just,
String fullName = Secur32Util.getUserNameEx(Secur32.EXTENDED_NAME_FORMAT.NameDisplay);
But it is the same, as the upper answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With