I've looked at several examples that are supposed to do this, and I don't see any difference between mine and others as far as core mechanics. Here is my code:
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;
}
}
The expected output is:
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
The actual output is:
Gathering available network data...
Result:
What am I doing wrong?
The pipe operator |
is interpreted the shell so does not form part of the command itself. In addition the command needs to appear in a single token to prevent the grep segment being evaluated separately:
String cmd[] = { "bash", "-c", "ifconfig |grep 'inet addr:'" };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.