![](/img/trans.png)
[英]View the console output of a running Java program, from another Java app
[英]Java program not displaying output from console
我已经看了几个可以做到这一点的例子,就核心机制而言,我和其他人之间没有任何区别。 这是我的代码:
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:
我究竟做错了什么?
管道操作员|
被解释为外壳,因此不构成命令本身的一部分。 另外,该命令需要出现在单个标记中,以防止对grep段进行单独评估:
String cmd[] = { "bash", "-c", "ifconfig |grep 'inet addr:'" };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.