从Java code运行批处理文件 [英] Run batch file from Java code
问题描述
我试图运行一个批处理文件,该文件是从我的Java可执行其他目录。我有以下的code:
I am trying to run a batch file that is in another directory from my Java executable. I have the following code :
try {
Process p = Runtime.getRuntime().exec("cmd /c start \"C:\\Program Files\\salesforce.com\\Data Loader\\cliq_process\\upsert\\upsert.bat\"") ;
} catch (IOException ex) {
}
其结果是,打开程序在程序在运行,并不会访问我公司提供的文件路径根目录下的cmd窗口。
The result is that the program opens a cmd window in the root directory where the program was run at and doesn't access the file path I provided.
推荐答案
而不是的Runtime.exec(字符串命令)
,您需要使用执行exec(字符串命令,字符串[] envp,文件目录)
方法签名:
Rather than Runtime.exec(String command)
, you need to use the exec(String command, String[] envp, File dir)
method signature:
Process p = Runtime.getRuntime().exec("cmd /c upsert.bat", null, new File("C:\\Program Files\\salesforce.com\\Data Loader\\cliq_process\\upsert"));
但就个人而言,我会使用的ProcessBuilder
来代替,这是一个有点冗长,但更容易使用和调试比的Runtime.exec( )
。
But personally, I'd use ProcessBuilder
instead, which is a little more verbose but much easier to use and debug than Runtime.exec()
.
List cmdAndArgs = Arrays.asList("cmd", "/c", "upsert.bat");
File dir = new File("C:/Program Files/salesforce.com/Data Loader/cliq_process/upsert");
ProcessBuilder pb = new ProcessBuilder(cmdAndArgs);
pb.directory(dir);
Process p = pb.start();
这篇关于从Java code运行批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!