小编典典

Java当前机器名和登录用户?

all

是否可以获得当前登录用户的名称(Windows/Unix)和机器的主机名?

我认为它只是一些静态环境类的属性。

我为用户名找到了这个

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

这对于机器名称:

import java.net.InetAddress;
...
String computerName;
...
try {
    computerName = InetAddress.getLocalHost().getHostName();
}

catch(Exception ex) {
    ...
}

第一个仅适用于Windows吗?

如果您没有设置主机名,第二个会做什么?


阅读 1343

收藏
2022-09-02

共1个答案

小编典典

获取当前登录的用户:

System.getProperty("user.name"); //platform independent

和机器的主机名:

java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());
2022-09-02