How to get current user name using Java

Many time we need name of user by which our java program is running. To do this we can simply access Java environment variables or we can use com.sun.security.auth.module.NTSystem class to do this. Here is example for getting current user(by which our java code is running).

Example 1, using java environment valiable

System.out.println(System.getProperty("user.name"));

 

Example 2, using NTSystem

com.sun.security.auth.module.NTSystem nsys = new com.sun.security.auth.module.NTSystem();
System.out.println(nsys.getName());

Example 2 will work only on windows systems.