[英]Running command manually with java (using cmd.exe)
So the following opens a new browser window when I put it in cmd manually: 因此,当我手动将其放入cmd时,以下内容将打开一个新的浏览器窗口:
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. 但是,当我尝试通过Java程序(参见下文)执行此操作时,命令提示符将打开并转到正确的目录,但不会打开新窗口。 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");
Try ProcessBuilder
instead of Runtime
: 尝试使用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();
See also: 也可以看看:
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. 如果那行不通,我建议尝试使用Apache Commons Exec库,因为我总是使用它。
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. 使用上面类似的方法,应将chrome.exe的完整路径添加为新参数,然后库将负责转义。
I run a chrome process using: 我使用以下方法运行chrome处理:
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.