Java中调用外部命令
public class ExecCommond{
public ExecCommond(){}
/**
  * 执行一条命令
  * @param execStr String 命令字符串
  * @return String 执行命令错误时的信息。
  */
 public static String  exec(String execStr) {
    Runtime runtime = Runtime.getRuntime(); 取得当前运行期对象
    String   outInfo=""; //执行错误的输出信息
    try {
          String[] args = new String[] {"sh", "-c", execStr};//执行linux下的命令
              //执行windows下的命令
//                   String[] args = new String[] {"cmd", "-c", execStr};
      Process proc = runtime.exec(args); //启动另一个进程来执行命令
      InputStream in = proc.getErrorStream();//得到错误信息输出。
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String line = "";
      while ( (line = br.readLine())
             != null) {
        outInfo = outInfo + line + "\n";
        System.out.println(outInfo);
      }
      // 检查命令是否失败。
 
      try {
        if (proc.waitFor() != 0) {
          System.err.println("exit value = " +
                             proc.exitValue());
        }
      }
      catch (InterruptedException e) {
        System.err.print(e);
        e.printStackTrace();
      }
    }
    catch (IOException e) {
      flag = false;
      System.out.println("exec error: " + e.getMessage());
      e.printStackTrace();
    }
    finally {
      return outInfo;
    }
  }
}