启动带空格的 CMD 命令 JAVA

Launch CMD command with spaces with JAVA

我想在 CMD 中使用 ProcessBuilder 执行,这是我的代码:

ProcessBuilder pb = new ProcessBuilder(
            "cmd /c start C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --headless --disable-gpu --print-to-pdf javaGen.pdf  file:///C:/Users/User/Desktop/template/template2.html");
pb.start();

但我不断收到:

Cannot run program "cmd /c start C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --headless --disable-gpu --print-to-pdf javaGen.pdf  file:///C:/Users/User/Desktop/template/template2.html": CreateProcess error=2, file not found

而且我确定 chrome.exe 和 template2.html 它们在各自的路径中。

编辑

我也试过这个:

Process p = Runtime.getRuntime().exec(
            "cmd /c start \"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe\" --headless --disable-gpu --print-to-pdf javaGen.pdf  file:///C:/Users/User/Desktop/template/template2.html");

我得到了:

windows can't find --headless

*编辑 2 *

我试过这个命令:

pb.command(new String[] { "cd \"Program Files (x86)\"", "cd Google\Chrome\Application\",
            "chrome.exe --headless --disable-gpu --print-to-pdf javaGen.pdf  file:///C:/Users/User/Desktop/template/template2.html" });
    pb.start();

我得到了:

Cannot run program "cd "Program Files (x86)"": CreateProcess error=2, File not found

要 运行 一个带有 cmd 的程序你只需要 cmd /c %programname%,但是你添加了 start 导致了问题。

将您的 ProcessBuilder 更改为:

ProcessBuilder pb = new ProcessBuilder(
            "cmd", "/c", "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "--headless", "--disable-gpu", "--print-to-pdf", "javaGen.pdf",  "file:///C:/Users/User/Desktop/template/template2.html");
pb.start();