Runtime.getRuntime().exec() execute two li

2019-05-18 12:46发布

问题:

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.