How to get Windows username in Java?

两盒软妹~` 提交于 2019-11-27 01:26:12

Lookup the system property "user.name".

String username = System.getProperty("user.name");

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()
Evgeniy Dorofeev

Two ways

  1. System.getProperty("user.name");

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!