Вопрос

So the following opens a new browser window when I put it in cmd manually:

cd C:/Program Files (x86)/Google/Chrome/Application&chrome.exe

However, when I tried to do this via a java program (see below), the command prompt opens and goes to the correct directory, but no new window opens. Any ideas of what I need to change?

    Runtime rt = Runtime.getRuntime();
    rt.exec("cmd.exe /c start cd C:/Program Files (x86)/Google/Chrome/Application&chrome.exe");
Это было полезно?

Решение 2

rt.exec("cmd.exe /c start cd \"C:/Program Files (x86)/Google/Chrome/Application&chrome.exe\"");

Not tested but this shall work, I just put the complete path in double quotes so that because of spaces it's not considered to be the next argument.

If that doesn't work, I suggest trying Apache Commons Exec library, because I always use that.

Here is some sample code from one of my applications :

CommandLine cmdLine = new CommandLine("cmd.exe");
                    cmdLine.addArgument("/c");
                    cmdLine.addArgument(".\\phantomjs\\nk\\batchbin\\casperjs.bat");
                    cmdLine.addArgument(".\\phantomjs\\nk\\batchbin\\dd.js");
                    cmdLine.addArgument(url);
                    cmdLine.addArgument(">" + rand);
                    DefaultExecutor executor = new DefaultExecutor();
                    int exitValue = executor.execute(cmdLine);

Using something like above the complete path to chrome.exe should be added as a new argument, and then the library will take care of escaping.

Другие советы

Try ProcessBuilderinstead of Runtime:

String command = "C:/Program Files (x86)/Google/Chrome/Application&chrome.exe";
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", command);
Process p = pb.start();

See also:

I run a chrome process using:

            ProcessBuilder builder = new ProcessBuilder();            
            builder.command("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "https://your url");            
            Process process = builder.start();
            int exitCode = process.waitFor();        
            assert exitCode == 0;      
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top