如何在 Java 中获取 Windows 用户名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19990038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Windows username in Java?
提问by Noah Cagle
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?
所以我想要做的是让我的 Java 找到登录 windows 的用户名,所以当我说这样一个方法时,它会返回用户名,就像我在名为 Noah 的用户中使用它一样,java 会返回“Noah”,如果我是用户 Amanda,Java 将返回“Amanda”。我该怎么做?
回答by rgettman
Lookup the system property "user.name".
查找系统属性“user.name”。
String username = System.getProperty("user.name");
Demonstration: Main.java
演示: 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>
回答by user987339
Try:
尝试:
String userName = System.getProperty("user.name");
or
或者
String userName = new com.sun.security.auth.module.NTSystem().getName()
回答by Evgeniy Dorofeev
Two ways
两种方式
System.getProperty("user.name");
System.getenv("USERNAME");
System.getProperty("user.name");
System.getenv("USERNAME");
Both are good for any OS
两者都适用于任何操作系统
回答by aaa
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
当应用程序在 Windows 服务上运行时,NTSystem.getName() 也会返回 SYSTEM。当应用程序在 Windows 服务上运行时,无法使用 NTSystem 获取用户名