【发布时间】:2015-12-09 13:55:21
【问题描述】:
我想使用Runtime.getRuntime().exec(String) 方法运行top -n 1 命令并将top -n 1 的输出输入到我的Java 程序中。
我尝试了使用BufferedReader 获取进程输出并使用返回的进程InputStream 的标准方法,但没有返回任何数据。
我也尝试了以下...
String path = "/home/user/Desktop/";
String cmd = "#!/bin/sh\ntop -n 1 > " + path + "output";
File shellCmd = new File(path + "topscript.sh");
PrintWriter writer = new PrintWriter(shellCmd);
writer.write(cmd);
writer.flush();
Runtime.getRuntime().exec("chmod +x " + shellCmd.getAbsolutePath());
Runtime.getRuntime().exec(shellCmd.getAbsolutePath());
创建shell script 和输出,但输出为空。但是,如果我随后加载我的local shell 并运行上面代码生成的script,我会在输出文件中得到正确的输出。
What's going wrong?
【问题讨论】:
-
你得到错误输出流吗?比如
p.getErrorStream(),内容是什么? -
@chengpohi 啊我不知道那个方法。它给了我
TERM environment variable not set. -
@chengpohi 所以它无法执行脚本但它可以创建脚本然后
chmod它。怎么chmod它却不能运行? -
因为当你使用 Java 运行一个 bash 脚本时,它会生成一个新的 shell 来运行它而不需要 env 变量。
-
考虑使用
top -n 1 -b使输出对文本文件更友好。