How to get Windows username in Java?

寵の児 提交于 2019-12-17 04:30:33

问题


So what I am trying to do is let my Java find the user's name that windows is logged in with, so when I would say such a method, it would return the users name, like I use it in the User called Noah, java would return "Noah" and if I were on the user Amanda, Java would return "Amanda". How would I do this?


回答1:


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>



回答2:


Try:

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

or

String userName = new com.sun.security.auth.module.NTSystem().getName()



回答3:


Two ways

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

  2. System.getenv("USERNAME");

Both are good for any OS




回答4:


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



来源:https://stackoverflow.com/questions/19990038/how-to-get-windows-username-in-java

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