by ampatspell
in Code
While digging in various existing Maven Mojos and looking for easiest way to run a separate java process from Maven Mojo, in exec-maven-plugin I’ve found reference to nice helper class from Plexus Common Utilities named Commandline.
So, to run java (or any other) process using CommandLine and CommandLineUtils classes:
import org.codehaus.plexus.util.cli.Commandline; /** * @parameter expression="${java.home}" * @required */ protected File javaHome; public void run() { Commandline cmd = new Commandline(); cmd.setExecutable(getJavaExecutable().getAbsolutePath()); cmd.setWorkingDirectory( ... ); cmd.addArguments( ... ); StreamConsumer stdout = ... int result = CommandLineUtils.executeCommandLine(cmd, stdout, stdout); } private File getJavaExecutable() { return new File(new File(javaHome, "bin"), "java"); }
<dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-utils</artifactId> <version>1.5.15</version> </dependency>
I’m not sure if it is the “Maven way” of getting path to java executable but it should work just fine in all Java-supported OS’es.