How to get Windows username in Java?

前端 未结 4 1598
别跟我提以往
别跟我提以往 2020-11-27 05:49

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

相关标签:
4条回答
  • 2020-11-27 06:15

    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>
    
    0 讨论(0)
  • 2020-11-27 06:16

    Try:

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

    or

    String userName = new com.sun.security.auth.module.NTSystem().getName()
    
    0 讨论(0)
  • 2020-11-27 06:27

    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

    0 讨论(0)
  • 2020-11-27 06:30

    Two ways

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

    2. System.getenv("USERNAME");

    Both are good for any OS

    0 讨论(0)
提交回复
热议问题