Java具有使用Runtime.exec对本地程序调用进行重定向的能力,但是用重定向或者管道进行命令调用将会出错。解决这一问题的办法是通过命令shell运行命令,将要输入的命令串弄成一个字符串数组,并且将它传送到命令shell。下面的例子是获取网关的函数:
private String getgateway()
{
String[] cmd = new String[] { "/bin/sh","-c", "route | grep -P \"^default.*eth0$\" | awk '{print $2}'" };
String gateway = null;
Process process;
try {
process = Runtime.getRuntime().exec(cmd);
InputStreamReader r = new InputStreamReader(process.getInputStream());
LineNumberReader returnData = new LineNumberReader(r);
gateway = returnData.readLine();
System.out.println(gateway);
} catch (IOException ex) {}
return gateway;
}