Issue
I want to run another process written in java. But I don't know how to do it. I searched the internet but only found how to start notepad. I have a class main, in it I want to start a new process ChildMain. How to do it ?
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
Process process = Runtime.getRuntime()
.exec("javac -cp src/child/ChildMain.java");
Thread.sleep(10000);
}
public class ChildMain {
public static void main(String[] args) {
// code
}
}
If anyone has an example or know how to do it, please tell me
Solution
For one, your code is trying to compile a Java source file, not run a Java class file. Get the correct command line, just as you did to start the initial process.
You can use the System Property "java.home" to find the java launcher command (assuming the JRE includes it - not all JREs will if they were made for a specific application with jlink
.)
Here is code to run an executable Jar file... the class path would need to be adjusted:
public class LaunchJavaProcess {
public static void main(String[] args) throws IOException {
String javaEXE = Path.of(System.getProperty("java.home"),
"bin",
System.getProperty("os.name").contains("Windows") ? "java.exe" : "java")
.toString();
ProcessBuilder pb = new ProcessBuilder(javaEXE, "-cp", ".", "-jar", "SomeExecutable.jar");
pb.inheritIO();
pb.start();
}
}
Answered By - swpalmer
Answer Checked By - Clifford M. (JavaFixing Volunteer)