如何在后台从 Java 代码运行命令行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11394394/
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 command line from Java code in the background?
提问by cHam
I have the following line to run a batch file,
我有以下行来运行批处理文件,
Process process = Runtime.getRuntime().exec("cmd /c start rake.bat");
But I want it to run in the background and not display the command line to the user. How can I change it to do this?
但我希望它在后台运行,而不是向用户显示命令行。我怎样才能改变它来做到这一点?
The problem is that the command window opens and intrupts the programs GUI. I just want the command window to not be visible while it is executing the batch file.
问题是命令窗口打开并中断程序 GUI。我只是希望命令窗口在执行批处理文件时不可见。
回答by David Kroukamp
Removing the 'start' completely will do what you want (as this is what is creating the window):
完全删除“开始”将执行您想要的操作(因为这就是创建窗口的内容):
Process process = Runtime.getRuntime().exec("cmd /c rake.bat");
I have tested this and it works, ofcourse if you want to communicate with the command prompt you'd have to have Input and Output streams, also not forgetting your Error stream As stated in the comment though removing 'start' on XP wont help (as it wont work).
我已经测试了这个并且它有效,当然,如果你想与命令提示符进行通信,你必须有输入和输出流,也不要忘记你的错误流如评论中所述,尽管在 XP 上删除“开始”不会有帮助(因为它不起作用)。
回答by Brian Agnew
I'm not quite sure what you mean by 'in the background'
我不太清楚你所说的“在后台”是什么意思
If you mean simply that the window isn't visible, this SO answermay be of use.
如果您的意思只是窗口不可见,则此 SO 答案可能有用。
If (however) you mean that you want your Java program to continue running whilst this executes, then you should spawn this off in a separate thread.
如果(但是)您的意思是希望 Java 程序在执行时继续运行,那么您应该在单独的线程中生成它。
Regardless of the above, be careful to capture your batch file's sdtout/stderr.
无论上述情况如何,请注意捕获批处理文件的 sdtout/stderr。
回答by Ramesh PVK
Process process = Runtime.getRuntime().exec("cmd /c start rake.bat");
If you are calling the above line from a java process to execute the batch file. This will by default run in background.
如果您从 java 进程调用上面的行来执行批处理文件。这将默认在后台运行。