Process process = Runtime.getRuntime().exec("ping www.stackabuse.com");
运行此代码将执行我们以字符串格式提供的命令。但是,运行此命令时看不到任何东西。
为了验证它是否正确运行,我们将保留该process对象。让我们用一个BufferedReader来看看发生了什么:
public static void printResults(Process process) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
或者
String mPingHostnameResultV4;
try {
try {
Process p4 = Runtime.getRuntime().exec("sysctl -w net.core.wmem_default=8388608");
int status4 = p4.waitFor();
if (status4 == 0) {
mPingHostnameResultV4 = "Pass";
} else {
mPingHostnameResultV4 = String.format("Fail(%d)", status4);
}
} catch (IOException e) {
mPingHostnameResultV4 = "Fail: IOException";
}
} catch (InterruptedException e) {
mPingHostnameResultV4 = "Fail: InterruptedException";
}
TranLog.d(TAG, "doTest2 mPingHostnameResultV4 =%s",mPingHostnameResultV4);
}
上边waitFor值为1,而值为0才是执行正常,那我怎么才能知道这个执行结果是因为什么出错的呢?可以把出错信息打印出来就行了,process对象 有一个异常流,打印一下就好了:
FileInputStream errorStream = (FileInputStream)process.getErrorStream();
InputStreamReader isr = new InputStreamReader(errorStream,"gbk");//读取
System.out.println(isr.getEncoding());
BufferedReader bufr = new BufferedReader(isr);//缓冲
String line = null;
while((line =bufr.readLine())!=null) {
System.out.println(line);
}
isr.close();