Java Runtime.getRuntime().exec() 执行带空格命令

可执行文件路径如果包含空格,则在java中不能被获取到。

此时Debug一下,会发现 project=null. project.waitFor 的返回值为1.但是去源路径单击bat文件是可以正常运行的,说明问题出在文件路径上。

将文件路径中的空格用双引号引起来就可以了

原先的代码

String batpath = file.getCanonicalPath() + "\resources\runTest.bat";
//run bat file
Process project = Runtime.getRuntime().exec("cmd.exe /c " + batpath.);
int exitcode=project.waitFor();
//kill the process
project.destroy();
logger.info(exitcode);

 修改后的代码

//run bat file
Process project = Runtime.getRuntime().exec("cmd.exe /c " + batpath.replaceAll(" ", "" ""));
原文地址:https://www.cnblogs.com/xriverside/p/4362541.html