亲宝软件园·资讯

展开

Java调用命令行并获取执行结果 Java简单实现调用命令行并获取执行结果示例

枫轩缘 人气:0

本文实例讲述了Java简单实现调用命令行并获取执行结果。分享给大家供大家参考,具体如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Command {
  public static void exeCmd(String commandStr) {
    BufferedReader br = null;
    try {
      Process p = Runtime.getRuntime().exec(commandStr);
      br = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line = null;
      StringBuilder sb = new StringBuilder();
      while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
      }
      System.out.println(sb.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
    finally
    {
      if (br != null)
      {
        try {
          br.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
  public static void main(String[] args) {
    String commandStr = "ping www.baidu.com";
    //String commandStr = "ipconfig";
    Command.exeCmd(commandStr);
  }
}

运行结果:

希望本文所述对大家java程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论