用Java执行Shell命令

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();
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值