Java Runtime.getRuntime()。exec和垂直条[重复]

时间:2021-10-16 20:30:45

This question already has an answer here:

这个问题在这里已有答案:

I try to run the following command to get only a line of memory status.

我尝试运行以下命令以仅获取一行内存状态。

Runtime.getRuntime().exec("free -m | grep 'Mem'");

But it returns all lines of result. The command after the vertical bar is not processed. I also try:

但它返回所有结果。不处理垂直条之后的命令。我也尝试:

Runtime.getRuntime().exec(new String[] { "free", "-m", "|", "grep", "Mem" });

And it doesn't work either.

它也不起作用。

1 个解决方案

#1


1  

Piping with the "|" is only possible in a shell, but if you do runtime.exec() you have no shell. It just executes the other process. Therefore the pipe gets simply ignored. In your case, you could solve this relatively simple by using a regex matcher in your java program to extract the results.

管道用“|”只能在shell中使用,但如果你执行runtime.exec()则没有shell。它只是执行另一个过程。因此管道被简单地忽略了。在您的情况下,您可以通过在java程序中使用正则表达式匹配器来提取结果来解决这个问题。

#1


1  

Piping with the "|" is only possible in a shell, but if you do runtime.exec() you have no shell. It just executes the other process. Therefore the pipe gets simply ignored. In your case, you could solve this relatively simple by using a regex matcher in your java program to extract the results.

管道用“|”只能在shell中使用,但如果你执行runtime.exec()则没有shell。它只是执行另一个过程。因此管道被简单地忽略了。在您的情况下,您可以通过在java程序中使用正则表达式匹配器来提取结果来解决这个问题。