How to get Windows username in Java?
Lookup the system property "user.name".
String username = System.getProperty("user.name");
- System Properties
- System.getProperty
Demonstration: Main.java
public class Main {
public static void main(String[] args) {
System.out.println(System.getProperty("user.name"));
}
}
Output:
c:\dev\src\misc>javac Main.java
c:\dev\src\misc>java Main
rgettman
c:\dev\src\misc>
Try:
String userName = System.getProperty("user.name");
or
String userName = new com.sun.security.auth.module.NTSystem().getName()
Two ways
System.getProperty("user.name");
System.getenv("USERNAME");
Both are good for any OS
NTSystem.getName() also returns SYSTEM when the app runs on a windows service. There is no means to get the username with NTSystem when the app is running on a windows service