我现在在一台Linux机器上。我有一个Java程序,它需要运行一些Linux命令,比如ps
、top
、ls
或者free -m
。
在Java中运行命令的方式如下:
Process p = Runtime.getRuntime().exec("free -m");
我该如何在Java程序中获取输出?我需要处理输出中的数据。
Process.getInputStream()
获取表示新创建的进程的标准输出(stdout)的 InputStream
。 Process p = Runtime.getRuntime().exec("my terminal command");
p.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
String output = "";
while ((line = buf.readLine()) != null) {
output += line + "\n";
}
System.out.println(output);
waitFor()
调用将会无限期地阻塞。 - Joachim Sauerpublic String RunLinuxGrepCommand(String command) {
String line = null;
String strstatus = "";
try {
String[] cmd = { "/bin/sh", "-c", command };
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = in.readLine()) != null) {
strstatus = line;
}
in.close();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
String stackTrace = sw.toString();
int lenoferrorstr = stackTrace.length();
if (lenoferrorstr > 500) {
strstatus = "Error:" + stackTrace.substring(0, 500);
} else {
strstatus = "Error:" + stackTrace.substring(0, lenoferrorstr - 1);
}
}
return strstatus;
}
这个函数将会返回任何Linux命令的结果。
public static void main(String[] args) {
CommandLineHelper obj = new CommandLineHelper();
String domainName = "google.com";
//in mac oxs
String command = "ping -c 3 " + domainName;
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
String result = ProcBuilder.run("free", "-m");
它还允许设置超时,以便您的应用程序不会被无法终止的外部命令阻塞。
free -m
的输出比top -n 1
的输出短得多,仍适合我在与@spoon的答案中提到的OS缓冲区。在尝试调用waitFor()
之前,您必须读取流的内容。有关详细信息,请参阅我链接的文章(如果您真的想使用Runtime.exec()
或ProcessBuilder
,则必须阅读它。没有其他方法)。 - Joachim Sauertop
的限制:它需要一个真正的终端作为输出,而不仅仅是一个流。你可以尝试添加-b
选项以批处理模式运行它。 - Joachim Sauer