问题
在我的Java应用程序中,我想运行一个名为"scons -Q implicit-deps-changed build\file_load_type export\file_load_type"的批处理文件
好像我甚至无法让我的批处理文件执行。我没有想法。
这就是我在Java中所拥有的:
Runtime.
getRuntime().
exec("build.bat", null, new File("."));
以前,我有一个我想要运行的Python Sconscript文件,但由于这不起作用,我决定通过批处理文件调用该脚本,但该方法尚未成功。
#1 热门回答(160 赞)
批处理文件不是可执行文件。他们需要一个应用程序来运行它们(即cmd)。
在UNIX上,脚本文件在文件的开头有shebang(#!)以指定执行它的程序。双击Windows是由Windows资源管理器执行的.CreateProcess对此一无所知。
Runtime.
getRuntime().
exec("cmd /c start \"\" build.bat");
注意:使用start \"\"命令,将打开一个单独的命令窗口,其中包含空白标题,批处理文件中的任何输出都将显示在那里。它也应该只使用`cmd / c build.bat",在这种情况下,如果需要,可以从Java中的子进程读取输出。
#2 热门回答(20 赞)
有时线程执行进程时间高于JVM线程等待进程时间,它会在你调用的进程需要一些时间进行处理时发生,请使用waitFor()命令,如下所示:
try{
Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");
p.waitFor();
}catch( IOException ex ){
//Validate the case the file can't be accesed (not enought permissions)
}catch( InterruptedException ex ){
//Validate the case the process is being stopped by some external situation
}
这样,JVM将停止,直到你正在调用的进程在继续执行线程执行堆栈之前完成。
#3 热门回答(18 赞)
Runtime runtime = Runtime.getRuntime();
try {
Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");
InputStream is = p1.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
} catch(IOException ioException) {
System.out.println(ioException.getMessage() );
}