我正在尝试使用 exec 函数。可执行文件的路径包含空格,这让我很伤心 我的代码如下所示
Runtime.getRuntime().exec("\"C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation.exe\"", null, new File("\"C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation\""));
执行此操作时,我收到异常 -
Cannot run program ""c:\Program"
如果有人能给我一些帮助来解决这个问题,我将不胜感激
提前致谢
最佳答案
来自Runtime.exec(String command, String[] envp, File dir)
:
Executes the specified string command in a separate process with the specified environment and working directory.
This is a convenience method. An invocation of the form
exec(command, envp, dir)
behaves in exactly the same way as the invocationexec(cmdarray, envp, dir)
, wherecmdarray
is an array of all the tokens incommand
.More precisely, the
command
string is broken into tokens using aStringTokenizer
created by the callnew StringTokenizer(command)
with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string arraycmdarray
, in the same order.
这意味着第一个字符串被分解为标记,无论外部引号如何。使用Runtime.exec(String[] cmdarray, String[] envp, File dir)
版本以避免可执行路径的标记化。
或者,使用ProcessBuilder
:
File d = new File("C:/Program Files (x86)/ASL/_ASL Software Suite_installation");
ProcessBuilder pb = new ProcessBuilder(d.getAbsolutePath() + "/main.exe");
Process p = pb.directory(d)
.start();
参见:
关于java - 将路径传递给 exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44647639/