问题:调用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;
}