使用带有JAVA的空格启动CMD命令

时间:2017-12-12 10:10:21

标签: java cmd processbuilder

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

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

1 个答案:

答案 0 :(得分:0)

要使用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();