2011-01-25 43 views

回答

11

您可以执行id命令并读取结果。

例如:

$ id -u jigar

输出:

可以执行命令通过

try { 
    String userName = System.getProperty("user.name"); 
    String command = "id -u "+userName; 
    Process child = Runtime.getRuntime().exec(command); 

    // Get the input stream and read from it 
    InputStream in = child.getInputStream(); 
    int c; 
    while ((c = in.read()) != -1) { 
     process((char)c); 
    } 
    in.close(); 
} catch (IOException e) { 
} 

source

+0

如果您执行“id -n” – 2011-01-25 16:42:19

+1

`id -u `将只会打印UID,解析起来会容易得多。 – dogbane 2011-01-25 16:44:05

2

如果你能够影响Java虚拟机是如何启动的,你可以切换的UID作为用户属性:

java -Duserid=$(id -u) CoolApp 

在你CoolApp,你可以简单地取ID:

System.getProperty("userid"); 

问候,

马丁。

1

只需打开/etc/passwd文件并搜索用户等于System.getProperty("user.name")的行。

1

另一种选择是使用JNI调用getuid()。

相关问题