如何在JavaExec中获取管道命令并返回输出?
当我应用命令时,我不会得到任何输出。如何在使用命令时获得输出,或者不同时使用这两种情况如何在JavaExec中获取管道命令并返回输出?,java,linux,fedora,Java,Linux,Fedora,当我应用命令时,我不会得到任何输出。如何在使用命令时获得输出,或者不同时使用这两种情况 public class test { public static void main(String args[]) { System.out.println( systemtest("ifconfig | awk 'BEGIN { FS = \"\n\"; RS = \"\" } { print $1 $2 }' | sed -e 's/ .*inet addr:/,/'
public class test
{
public static void main(String args[])
{
System.out.println(
systemtest("ifconfig | awk 'BEGIN { FS = \"\n\"; RS = \"\" } { print $1 $2 }' | sed -e 's/ .*inet addr:/,/' -e 's/ .*//'"));
}
public static String systemtest(String cmds)
{
String value = "";
try
{
String cmd[] = {
"/bin/sh",
"-c",
cmds
};
Process p=Runtime.getRuntime().exec(cmd);
// Try 0: here? wrong
//p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
// Try 1: here?
//p.waitFor();
while(line!=null)
{
value += line + "\n";
line=reader.readLine();
}
// Try 2: here?
p.waitFor();
} catch(IOException e1) {
} catch(InterruptedException e2) {
}
return value;
}
您需要了解如何处理stdout、stderr和流管道。 或者,您可能有兴趣查看和 我希望它能帮助你。
祝你好运 在调用
p.waitFor()
之前,需要读取命令的输出
事实:
- 外部命令的输出通过操作系统级别的“管道”传递
- 管道具有有限的缓冲量
- 如果某个生产者进程试图写入“已满”的管道,则该进程将被迫等待,直到使用者进程从该管道读取了一些数据
(即使这不是您这次出现问题的真正原因,也可能是其他时候。在读取/写入外部进程时,请注意死锁。)p.waitFor();我在while循环之后或while循环之前的最后一行中更改了这个。但结果是一样的。我还没有得到输出,但一旦调用systemtest(“ifconfig”);它总是输出。编辑了我正在尝试的命令:ifconfig | awk'BEGIN{FS=\“\n\”;RS=\“\”}{print$1$2}'| sed-e's/*inet addr:/,/'-e's/*/'尝试一些更简单的方法,比如
systemtest(“ifconfig | cat”)
。我觉得问题在于反斜杠。如前所述,在shell命令中,ASCII换行符的位置看起来是非法的。我现在处于Windows状态,因此无法轻松检查此项…Commons CLI没有帮助,因为这是一个解析命令行的库。不支持生成命令行或进程处理。@a.H.我无法识别所问问题与您的评论之间的相关性。请解释。问题是关于“我如何执行程序”。Commons CLI是关于“当我实现一个程序时,如何解析命令行。”@a.H.我的道歉!我是说下议院执行官。。。(可与Commons CLI结合使用)