Runtime.getRuntime().exec() execute two lines?

跟風遠走 提交于 2019-12-12 10:09:36

问题


I need to run two lines in Runtime.getRuntime().exec(), this two:

cd %CMS_HOME%
ant deploy

Now is it possible to make a .bat file, but I think it is useless for two lines, is muss be easier! Someone any idea?


回答1:


Put it in a .bat file. It's not useless; that's just how Runtime.exec works.

You should look into using the ProcessBuilder class instead of Runtime.exec(). It was introduced in JDK 5 as the successor to Runtime.exec().




回答2:


Invoke the task programmatically from Java:

File buildFile = new File("build.xml");
Project p = new Project();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
p.init();
ProjectHelper helper = ProjectHelper.getProjectHelper();
p.addReference("ant.projectHelper", helper);
helper.parse(p, buildFile);
p.executeTarget(p.getDefaultTarget());



回答3:


You can use Runtime.exec(String command, String[] envp, File dir) to execute ant deploy in a dir folder.

P.S. Executing ant, which is a java program, using a batch file from another java program is a little bit weird. You can run it just as a java class...




回答4:


When you are running external application you have to behavior according to the rules of target operating system.

In your case you want to run 2 commands on windows, so you have to say:

cd TheDir && ant

Try it first in command line. Then to make it working run this command with prefix cmd from java:

cmd /c cd TheDir && ant

Alternatively you can use pure java solution. Use ProcessBuilder instead of Runtime.exec(). ProcessBuilder allows you to set working directory, so then you can run ant directly.

And the last point. Actually you do not have to run external process at all. Ant is java application. You can run its main() method directly from you application and specify all needed parameters.



来源:https://stackoverflow.com/questions/9680968/runtime-getruntime-exec-execute-two-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!