如何从我的 Java 应用程序运行批处理文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/615948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I run a batch file from my Java Application?
提问by Amara
In my Java application, I want to run a batch file that calls "scons -Q implicit-deps-changed build\file_load_type export\file_load_type
"
在我的 Java 应用程序中,我想运行一个名为“ scons -Q implicit-deps-changed build\file_load_type export\file_load_type
”的批处理文件
It seems that I can't even get my batch file to execute. I'm out of ideas.
似乎我什至无法让我的批处理文件执行。我没有想法了。
This is what I have in Java:
这是我在 Java 中所拥有的:
Runtime.
getRuntime().
exec("build.bat", null, new File("."));
Previously, I had a Python Sconscript file that I wanted to run but since that didn't work I decided I would call the script via a batch file but that method has not been successful as of yet.
以前,我有一个想要运行的 Python Sconscript 文件,但由于它不起作用,我决定通过批处理文件调用该脚本,但该方法尚未成功。
采纳答案by Paulo Guedes
Batch files are not an executable. They need an application to run them (i.e. cmd).
批处理文件不是可执行文件。他们需要一个应用程序来运行它们(即 cmd)。
On UNIX, the script file has shebang (#!) at the start of a file to specify the program that executes it. Double-clicking in Windows is performed by Windows Explorer. CreateProcess
does not know anything about that.
在 UNIX 上,脚本文件在文件开头有 shebang (#!) 以指定执行它的程序。在 Windows 中双击由 Windows 资源管理器执行。 CreateProcess
对此一无所知。
Runtime.
getRuntime().
exec("cmd /c start \"\" build.bat");
Note: With the start \"\"
command, a separate command window will be opened with a blank title and any output from the batch file will be displayed there. It should also work with just `cmd /c build.bat", in which case the output can be read from the sub-process in Java if desired.
注意:使用该start \"\"
命令,将打开一个单独的命令窗口,标题为空白,批处理文件的任何输出都将显示在那里。它也应该只与“cmd /c build.bat”一起工作,在这种情况下,如果需要,可以从 Java 的子进程中读取输出。
回答by Eli Courtwright
The executable used to run batch scripts is cmd.exe
which uses the /c
flag to specify the name of the batch file to run:
用于运行批处理脚本的可执行文件是cmd.exe
使用/c
标志来指定要运行的批处理文件的名称:
Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "build.bat"});
Theoretically you should also be able to run Scons in this manner, though I haven't tested this:
从理论上讲,您也应该能够以这种方式运行 Scons,尽管我尚未对此进行测试:
Runtime.getRuntime().exec(new String[]{"scons", "-Q", "implicit-deps-changed", "build\file_load_type", "export\file_load_type"});
EDIT: Amara, you say that this isn't working. The error you listed is the error you'd get when running Java from a Cygwin terminal on a Windows box; is this what you're doing? The problem with that is that Windows and Cygwin have different paths, so the Windows version of Java won't find the scons executable on your Cygwin path. I can explain further if this turns out to be your problem.
编辑:阿马拉,你说这行不通。您列出的错误是在 Windows 机器上从 Cygwin 终端运行 Java 时遇到的错误;这是你在做什么?问题在于 Windows 和 Cygwin 具有不同的路径,因此 Java 的 Windows 版本不会在您的 Cygwin 路径上找到 scons 可执行文件。如果结果证明这是您的问题,我可以进一步解释。
回答by basszero
ProcessBuilderis the Java 5/6 way to run external processes.
ProcessBuilder是运行外部进程的 Java 5/6 方式。
回答by Isha
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() );
}
回答by Juan Carlos Alpízar
Sometimes the thread execution process time is higher than JVM thread waiting process time, it use to happen when the process you're invoking takes some time to be processed, use the waitFor() command as follows:
有时线程执行进程的时间比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
}
This way the JVM will stop until the process you're invoking is done before it continue with the thread execution stack.
这样,JVM 将停止,直到您调用的进程完成,然后才继续执行线程执行堆栈。
回答by Abbia
To run batch files using java if that's you're talking about...
如果您正在谈论使用 java 运行批处理文件...
String path="cmd /c start d:\sample\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`
This should do it.
这应该这样做。
回答by Suren
Process p = Runtime.getRuntime().exec(
new String[]{"cmd", "/C", "orgreg.bat"},
null,
new File("D://TEST//home//libs//"));
tested with jdk1.5 and jdk1.6
用 jdk1.5 和 jdk1.6 测试
This was working fine for me, hope it helps others too. to get this i have struggled more days. :(
这对我来说很好用,希望它也能帮助其他人。为了得到这个,我挣扎了更多天。:(
回答by bharath
The following is working fine:
以下工作正常:
String path="cmd /c start d:\sample\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);
回答by Ben Jost
I had the same issue. However sometimes CMD failed to run my files. That's why i create a temp.bat on my desktop, next this temp.bat is going to run my file, and next the temp file is going to be deleted.
我遇到过同样的问题。但是有时 CMD 无法运行我的文件。这就是为什么我在桌面上创建一个 temp.bat,接下来这个 temp.bat 将运行我的文件,接下来将删除 temp 文件。
I know this is a bigger code, however worked for me in 100% when even Runtime.getRuntime().exec() failed.
我知道这是一个更大的代码,但是当 Runtime.getRuntime().exec() 失败时,我 100% 对我有用。
// creating a string for the Userprofile (either C:\Admin or whatever)
String userprofile = System.getenv("USERPROFILE");
BufferedWriter writer = null;
try {
//create a temporary file
File logFile = new File(userprofile+"\Desktop\temp.bat");
writer = new BufferedWriter(new FileWriter(logFile));
// Here comes the lines for the batch file!
// First line is @echo off
// Next line is the directory of our file
// Then we open our file in that directory and exit the cmd
// To seperate each line, please use \r\n
writer.write("cd %ProgramFiles(x86)%\SOME_FOLDER \r\nstart xyz.bat \r\nexit");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
// running our temp.bat file
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec("cmd /c start \"\" \""+userprofile+"\Desktop\temp.bat" );
pr.getOutputStream().close();
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
// deleting our temp file
File databl = new File(userprofile+"\Desktop\temp.bat");
databl.delete();
回答by ???? ??? ????
This code will execute two commands.bat that exist in the path C:/folders/folder.
此代码将执行路径 C:/folders/folder 中存在的两个 commands.bat。
Runtime.getRuntime().exec("cd C:/folders/folder & call commands.bat");