exec参数里面路径带空格问题

问题:调用Runtime对象的exec方法,经常遇到路径带空格的问题,导致报错

解决方法:路径的空格前后加双引号

例子:

 

  public static void main(String args[]) throws Exception
  {
    StringBuffer sb = new StringBuffer(250);
    String exePath = "D://Program Files//test//Pdf2Cebx.exe";
    String tempSrcPath = "D://Program Files//test//38965.pdf";
    String tempDestPath = "D://Program Files//test//38965.cebx";
    sb.append(exePath.replaceAll(" ", "/" /"")).append(" ").append(
        tempSrcPath.replaceAll(" ", "/" /"")).append(" ").append(
        tempDestPath.replaceAll(" ", "/" /""));


    ShellResult sr = ShellExecutor.execute(sb.toString());
    if (sr.getResult() == 0)
    {
      File destFile = new File("D://Program Files//test//38965.cebx");

      if (destFile.exists())
        System.out.println("SUCCESS!");
      else
        System.out.println("FAIL!");
    }
    else
    {
      System.out.println("FAIL!");
    }
  }
    public static ShellResult execute(String givenCmd) throws Exception
  {
    Global.logger.debug(givenCmd);
   
    int exitVal = -99;
    ShellResult sr = null;
    try
    {
      sr = new ShellResult();
      String osName = System.getProperty("os.name");
      String[] cmd = new String[3];
      if (osName.startsWith("Windows"))
      {
        if (osName.equals("Windows 95"))
        {
          cmd[0] = "command.com ";
          cmd[1] = "/C ";
          cmd[2] = givenCmd;
        }
        else
        {
          cmd[0] = "cmd.exe ";
          cmd[1] = "/C ";
          cmd[2] = givenCmd;
        }
      }
      else
      {
        cmd[0] = "";
        cmd[1] = "";
        cmd[2] = givenCmd;
      }

      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec(cmd[0] + "" + cmd[1] + "" + cmd[2]);

      // 开始获取输出
      ByteArrayOutputStream bss = new ByteArrayOutputStream();
      //TODO 对于动态GIF 此处会无返回
      InputStream ein = proc.getErrorStream();
      CopyUtils.copy(ein, bss);
      String errMsg = new String(bss.toByteArray());
      bss.close();
      ein.close();
      ein = proc.getInputStream();
      CopyUtils.copy(ein, bss);
      String outputMsg = new String(bss.toByteArray());
      bss.close();
      ein.close();

      // 获取结束
      exitVal = proc.waitFor();

      sr.setResult(exitVal);
      sr.setErrorMsg(errMsg);
      sr.setOutputMsg(outputMsg);
      if (exitVal != 0)
      {
        // 非正常结束
        throw new Exception("[ERROR_MSG:" +  errMsg  +"],[OUPUT_MSG:" + outputMsg
          + "]");
      }
    }
    catch (Exception t)
    {
      throw t;
    }
    return sr;
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值