我已经看过几个应该这样做的例子,而且就核心机制而言,我并没有看到我和其他人之间的任何差异。这是我的代码:
public class Console
{
public static void main(String[] args) throws IOException, InterruptedException{
Runtime rt = Runtime.getRuntime();
Process ps;
System.out.println("Gathering available network data...");
String cmd[] = {"ifconfig","|","grep","'inet addr:'"};
ps = rt.exec(cmd);
getOutput(cmd,ps);
}
public static String getOutput(String[] c, Process p) throws IOException, InterruptedException
{
Process ps = p;
String output="";
BufferedReader readerStd = new BufferedReader(new InputStreamReader(ps.getInputStream()));
BufferedReader readerErr = new BufferedReader(new InputStreamReader(ps.getInputStream()));
String line = null;
System.out.println("Result:");
while ((line = readerStd.readLine()) != null) {
System.out.println(line);
output+=line+"\n";
}
if((line = readerErr.readLine()) != null)
{
System.out.println("------ Std Err -------");
System.out.println(line);
while ((line = readerErr.readLine()) != null)
{
System.out.println(line);
}
}
return output;
}
}
预期输出为:
Gathering available network data...
Result:
inet addr:10.40.2.234 Bcast:10.40.2.255 Mask:255.255.255.0
inet addr:127.0.0.1 Mask:255.0.0.0
实际输出是:
Gathering available network data...
Result:
我做错了什么?
答案 0 :(得分:0)
管道运算符|
被解释为shell,因此不构成命令本身的一部分。此外,该命令需要出现在单个标记中,以防止单独评估grep段:
String cmd[] = { "bash", "-c", "ifconfig |grep 'inet addr:'" };