Java Runtime.getRuntime().exec 和竖线 [英] Java Runtime.getRuntime().exec and the vertical bar

查看:68
本文介绍了Java Runtime.getRuntime().exec 和竖线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

它也不起作用.

推荐答案

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

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.

这篇关于Java Runtime.getRuntime().exec 和竖线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆