参数包含空格的运行时 exec

Runtime exec with arguments containing spaces

我有一个应用程序,我正尝试通过 Runtime.exec() 调用 运行。

由于一些参数有空格,我怎样才能正确地转义参数,使其在 Linux 和 Windows 中都有效?我知道 Windows,您通常在带空格的字符串周围使用双引号,而 linux 使用斜杠。

有了空格,我希望我正在 运行ning 的程序(Windows' xcopy 现在)几乎立即到 return 并指出参数的数量是错误的。但是,waitFor() 调用挂起。

String[] commandArray = new String[3];
commandArray[0] = applicationPath;
commandArray[1] = someFileWhichMayHaveSpaces;
commandArray[2] = anotherFileWhichMayHaveSpaces;

Process appProcess = Runtime.getRuntime().exec(commandArray);
int returnCode = appProcess.waitFor();

几周前我开发的应用程序遇到了同样的问题。最终,我放弃了使用原始 Runtime.exec() (pitfalls of Runtime.exec()) and decided to use Apache Commons Exec library. It helped to solve various problems out of box and random hanging during execution. Its addArguments() method takes handleQuoting parameter, so I created a simple util method that checks the OS and I request handling quoting for Windows, while for Linux I pass false. If you want some working examples, there are some tutorials on the library website. You may also take a look at my class that uses commons-exec in the Open LaTeX Studio 项目。

看起来 args 中的空格完全没有问题,至少在 Windows 环境中进行了测试。问题是如果复制源是文件或目录,xcopy 会提示 /halting 回答问题。我以为它在空间上窒息,但显然不是。我能够按原样使用问题中的代码,而不必使用 ProcessBuilder。

在 Windows 上,如果有疑问,您应该使用 Runtime.exec 的重载之一,它采用字符串而不是字符串数组作为命令行参数。这允许您自己为新进程构建命令行字符串,因此您可以确保语法正确。

如果使用数组方法,Java必须将数组转换为单个字符串。它将使用标准算法执行此操作,该算法假定目标进程使用 Microsoft C 运行时命令行解析器(或兼容的解析器)。这 通常 没问题,但并非总是如此。