2013-07-30 23 views
0

所以下面打开一个新的浏览器窗口,当我把它在CMD手动:运行命令手动与Java(使用CMD.EXE)

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

然而,当我试图通过Java程序来做到这一点(见下),命令提示符打开并进入正确的目录,但不会打开新窗口。我需要改变什么想法?

Runtime rt = Runtime.getRuntime(); 
    rt.exec("cmd.exe /c start cd C:/Program Files (x86)/Google/Chrome/Application&chrome.exe"); 
+0

你有没有试过rt.exec(“C:/ Program Files(x86)/Google/Chrome/Application/chrome.exe”); – Katona

+0

我确实尝试过,并且该机器似乎在C:/ Program中引发错误。它没有超越那个。 – austinthemassive

+0

它似乎Runtime.exec(字符串)标记化字符串,但Runtime.exec(字符串[])不是,所以我最后的猜测会是rt.exec(新字符串[] {“C:/ Program Files文件(x86)/谷歌/Chrome/Application/chrome.exe“}); – Katona

回答

1

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

未测试,但这应该工作,我只是把双引号的完整路径,以便由于空间它不被认为是下一个参数。

如果这不起作用,我建议尝试Apache Commons Exec库,因为我总是使用它。

这里是我的应用程序之一一些示例代码:

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

使用类似的完整路径上面的chrome.exe应该被添加为新的参数,然后该库将采取逃避的护理。

+0

我其实刚刚解决了这个问题,使用Apache Commons库(由其他来源推荐)。谢谢你的提示! – austinthemassive

2

尝试ProcessBuilder而不是Runtime

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

参见:

+0

我会给这个镜头。 Runtime和ProcessBuilder之间有什么区别,在你看来,我应该什么时候使用它们? – austinthemassive

+0

老实说,我不知道究竟有什么区别,但我使用'ProcessBuilder'主要是因为你可以使用'pb.environment()。put(key,value)'设置环境变量。另外,使用多个参数分别运行命令会更简单,而不是将它们写入一个大字符串中。 – dic19