A simple way to launch any command is:
public class Launch
{
public static void exec(String[] cmd) throws InterruptedException, IOException
{
System.out.println("exec "+Arrays.toString(cmd));
Path tmpdir = Path.of(System.getProperty("java.io.tmpdir"));
ProcessBuilder pb = new ProcessBuilder(cmd);
Path out = tmpdir.resolve(cmd[0]+"-stdout.log");
Path err = tmpdir.resolve(cmd[0]+"-stderr.log");
pb.redirectError(out.toFile());
pb.redirectOutput(err.toFile());
Process p = pb.start();
int rc = p.waitFor();
System.out.println("Exit "+rc +' '+(rc == 0 ? "OK":"**** ERROR ****")
+" STDOUT \""+Files.readString(out)+'"'
+" STDERR \""+Files.readString(err)+'"');
System.out.println();
}
}
And to launch a java application:
public class LaunchJava
{
public static void main(String[] args) throws InterruptedException, IOException
{
String java = Path.of(System.getProperty("java.home"),"bin", "java").toAbsolutePath().toString();
String mainClass = "somepackage.MainClass";
List<String> classpath = List.of("C:\\jars\\xyz.jar", "C:\\somedirectory");
List<String> params = List.of("PARAM1","PARAM2","PARAM2");
ArrayList<String> cmd = new ArrayList<>();
cmd.add(java);
cmd.add("--class-path");
cmd.add(String.join(File.pathSeparator, classpath));
cmd.add(mainClass);
cmd.addAll(params);
Launch.exec(cmd.toArray(String[]::new));
}
}