Java Runtime.getRuntime.exec()返回null但在shell中返回有效的String

时间:2015-11-24 19:13:40

标签: java linux shell runtime.exec

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

/usr/bin/logname
scott

但是我用java编写的代码与java中的String不一样。

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);
}

当我创建对象时,我看到null的值为currentUser,这意味着stdInput.readLine();没有输出任何内容。

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

1 个答案:

答案 0 :(得分:1)

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

System.getProperty("user.name") 

至少是平台无关的?为什么要编写像Java这样的语言特定的unix代码?