Search code examples
javacmdprocessbuilder

Launch CMD command with spaces with JAVA


I want to excute in CMD with ProcessBuilder and here's my code :

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();

But I keep getting :

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

And I'm sure about chrome.exe and template2.html that they're in there respective paths.

EDIT

I also tried this :

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");

And I got :

windows can't find --headless

*EDIT 2 *

I tried this command :

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();

And I got :

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

Solution

  • To run a program with cmd you only need cmd /c %programname%, but you added start which caused the problem.

    Change your ProcessBuilder to:

    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();