java中执行Windows或Unix命令

package com.nantian.itbms;

/**
 * 执行windows 命令或unix shell命令
 * @author panhong
 *
 */
public class WinUnixShell {

 public static void main(String[] args0) {
   String cmd="ping www.163.com";
  // String cmd="ipconfig";
  //String cmd = "ping 192.168.0.1";
  // String cmd="ipconfig";
  String result;
  try {
   result = exec(cmd);
   System.out.println("返回:\r\n" + result);
  } catch (Exception e) {
   System.out.println("执行出错:\r\n" + e.getMessage());
  }

 }

 /**
  * 执行window cmd或unix shell命令,如ipconfig
  *
  * @param youCmd
  * @return 执行命令状态

  * @throws Exception
  */
 public static String exec(String youCmd) throws Exception {
  String msg = null;
  if (youCmd == null || youCmd.length() < 1) {
   throw new Exception("请输入有效命令行命令");
  }

  try {
   hostInfo hostInfo = new hostInfo();
   String osName = hostInfo.getsysTYpe();
   String[] cmd = new String[3];
   if (("Windows 2000").equalsIgnoreCase(osName)
     || "Windows XP".equalsIgnoreCase(osName)) {
    cmd[0] = "cmd.exe";
    cmd[1] = "/C";
    cmd[2] = youCmd;
   } else if (osName.equals("Windows 95")) {
    cmd[0] = "command.com";
    cmd[1] = "/C";
    cmd[2] = youCmd;
   }
   if(osName.indexOf("unix")!=-1){ //unix操作系统
    cmd[0] = "ls";
    cmd[1] = "/C";
    cmd[2] = youCmd;
   }

    System.out.println("cmd:\r\n" + cmd[0] + " " + cmd[1] + " " +
    cmd[2]);
   Runtime rt = Runtime.getRuntime();
   Process proc = rt.exec(cmd);
   InputStreamPipe errorGobbler = new InputStreamPipe(proc
     .getErrorStream(), "ERROR");
   InputStreamPipe outputGobbler = new InputStreamPipe(proc
     .getInputStream(), "OUTPUT");
   errorGobbler.start();
   outputGobbler.start();

   int exitVal = proc.waitFor();// 等待事情干完,返回值0表示正确返回
   if (exitVal != 0) {
    msg = "失败";
    throw new Exception(errorGobbler.getOutputMsg()
      + "(异常退出值exitVal=" + exitVal + ")");
   } else {
    msg = outputGobbler.getOutputMsg();//返回命令执行结果
   }
  } catch (Exception e) {
   throw new Exception(e.getMessage());
  }

  return msg;
 }
}

你可能感兴趣的:(java,c,windows,unix,XP)