gpt4 book ai didi

Java Runtime.getRuntime.exec() 返回 null 但在 shell 中返回有效字符串

转载 作者:太空宇宙 更新时间:2023-11-04 10:43:52 25 4
gpt4 key购买 nike

我一直在编写一个类来查找真实的用户 ID,使用 linux 二进制 /usr/bin/logname 返回与我的 TTY 关联的当前用户。该命令在 shell 中运行良好。

/usr/bin/logname
scott

但我无法使用我编写的以下代码获得与 Java 中的字符串相同的值。

private String currentUser;
public void getRealUser() throws Exception{
String cmd = "/usr/bin/logname";
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
this.currentUser = stdInput.readLine();
System.out.println(currentUser);
}

当我创建对象时,我看到值 currentUsernull,这意味着 stdInput.readLine(); 没有输出任何东西。

请让我知道我做错了什么。

最佳答案

这不是直接回答你的问题,但你试过了吗:

System.getProperty("user.name") 

哪个至少与平台无关?为什么要用 Java 等语言编写特定于 unix 的代码?

关于Java Runtime.getRuntime.exec() 返回 null 但在 shell 中返回有效字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com