It is a bit strange but you can run the second program without forking it. Just calling the main method in it. So forget the runtime section and do this:

sam2.main(new String[0]);

Of course this way you must compile sam2 at compile time

Answer from András Tóth on Stack Overflow
Top answer
1 of 5
22

It is a bit strange but you can run the second program without forking it. Just calling the main method in it. So forget the runtime section and do this:

sam2.main(new String[0]);

Of course this way you must compile sam2 at compile time

2 of 5
15

Each process needs to be allowed to run and finish. You can use Process#waitFor for this purpose. Equally, you need to consume any output from the process at the same time. waitFor will block so you will need use a Thread to read the input (and if you need to, write output to the process)

Depending on the location of the java/class file, you may also need to specify a starting folder from which the execution of the process can start.

Most of this significantly easier using ProcessBuilder

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class CompileAndRun {

    public static void main(String[] args) {
        new CompileAndRun();
    }

    public CompileAndRun() {
        try {
            int result = compile("compileandrun/HelloWorld.java");
            System.out.println("javac returned " + result);
            result = run("compileandrun.HelloWorld");
        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    public int run(String clazz) throws IOException, InterruptedException {        
        ProcessBuilder pb = new ProcessBuilder("java", clazz);
        pb.redirectError();
        pb.directory(new File("src"));
        Process p = pb.start();
        InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
        consumer.start();

        int result = p.waitFor();

        consumer.join();

        System.out.println(consumer.getOutput());

        return result;
    }

    public int compile(String file) throws IOException, InterruptedException {        
        ProcessBuilder pb = new ProcessBuilder("javac", file);
        pb.redirectError();
        pb.directory(new File("src"));
        Process p = pb.start();
        InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
        consumer.start();

        int result = p.waitFor();

        consumer.join();

        System.out.println(consumer.getOutput());

        return result;        
    }

    public class InputStreamConsumer extends Thread {

        private InputStream is;
        private IOException exp;
        private StringBuilder output;

        public InputStreamConsumer(InputStream is) {
            this.is = is;
        }

        @Override
        public void run() {
            int in = -1;
            output = new StringBuilder(64);
            try {
                while ((in = is.read()) != -1) {
                    output.append((char) in);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                exp = ex;
            }
        }

        public StringBuilder getOutput() {
            return output;
        }

        public IOException getException() {
            return exp;
        }
    }
}

Now obviously, you should check the return results of the processes, and may be produce a better mechanism for interacting with the processes, but that's the basic idea...

🌐
DigitalOcean
digitalocean.com › community › tutorials › compile-run-java-program-another-java-program
How to Compile and Run Java Program from another Java Program | DigitalOcean
August 4, 2022 - Have you ever thought if it’s possible to compile and run a java program from another java program? We can use Runtime.exec(String cmd) to issue commands to the underlying operating system.
Discussions

How do I run a .java file from another .java file?
I found a solution: fileName.main(args) does what I need. More on reddit.com
🌐 r/learnjava
6
5
December 7, 2020
How to run a java program from another java program? - Stack Overflow
So I have a java program of a game. I want to have a different program and when you click on a button there that java program closes and starts the program with the game. But I have no idea how I c... More on stackoverflow.com
🌐 stackoverflow.com
How to run a .java program from another .java program? - Stack Overflow
I tried it by extending class name of another program and calling it into the main function, when i go to compile and run it, doesn't give an error but also doesn't give an output of another java p... More on stackoverflow.com
🌐 stackoverflow.com
How to call a java program from another java program? - Stack Overflow
0 How to create a java program that runs another java program which will recieve input from a text file? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Centron
centron.de › startseite › how to compile java program from another java program
Compile Java Program: A Step-by-Step Guide
February 4, 2025 - Using the Runtime.exec method enables us to execute one Java program using another, making it a versatile tool for automating tasks or creating dynamic program workflows. The printLines() and runProcess() methods used in this example are adapted ...
🌐
Coderanch
coderanch.com › t › 703991 › java › Running-Java-function-Java-program
Running a Java function from another Java program on different computer in a network (Java in General forum at Coderanch)
December 24, 2018 - Now make a separate second simple java Program named Java2 with only a jButton, when I run this Java2 on another PC that is in the same LAN / WLAN network with the Computer A, when I press the jButton on the Java2 app it will do the same to the labelNum in the Java1 program ran on the Computer ...
🌐
Reddit
reddit.com › r/learnjava › how do i run a .java file from another .java file?
r/learnjava on Reddit: How do I run a .java file from another .java file?
December 7, 2020 -

I have a Java program that takes user input from the console. Based on user input, one of two .java files in the same package need to be executed. I've already tried:

try { 
    // Command to create an external process 
    String command = "C:\\Users\\myname\\eclipseworkspace\\pr\\src\\myPackage\\ViewCustomers.java"; 
	  
    // Running the above command 
    Runtime run  = Runtime.getRuntime(); 
    Process proc = run.exec(command); 
} catch (IOException e){ 
    e.printStackTrace(); 
} 

but this gives Cannot run program ... CreateProcess error=193, %1 is not a valid Win32 application.

I know this should be possible, but I can't remember how to do it and my research is only turning up results on how to run programs from the command line, which is not what I need. How can I do this?

Thanks for any help, I really appreciate it.

Find elsewhere
🌐
CodingTechRoom
codingtechroom.com › question › how-to-execute-a-java-program-from-another-java-program-a-step-by-step-guide
How to Execute One Java Program from Another Java Program - CodingTechRoom
To execute one Java program from another, you can utilize the ProcessBuilder or Runtime classes, which allow you to start a new process.
🌐
Stack Overflow
stackoverflow.com › questions › 24839592 › how-to-run-a-java-program-from-another-java-program
How to run a .java program from another .java program? - Stack Overflow
... Got it! i was extending it with main class name which is wrong thing to do, now get to know to run a java program from another java program is by extending it's class object name, that is what we call into the main function.
Top answer
1 of 2
6

First, compile your code. I do not think you really want to compile class B from class A as you have written. This almost does not make any sense.

Now, since both are java classes you can just call methods of one class from another directly. If however your really mean that 2 classes are independent programs, so that each one has its own main method you can run one application from another using either Runtime.getRuntime().exec(...) or using ProcessBuilder.

Please pay attention on words really I wrote. I am pretty sure you do not want to call one java program from another. Most chances are that you want to call methods of one class from another, so do this.

2 of 2
0

@AlexR: IMO this is a valid scenario. Let's assume you want to upload a code from some where and then execute it, and validate the output.

Try using the below mentioned code:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    public class A {

      public static void main(String[] args) {
        try {
            Process processCompile = Runtime.getRuntime().exec("javac B.java");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Process processRun = null;
        try {
            processRun = Runtime.getRuntime().exec("java B");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            printLines(" stdout:", processRun.getInputStream());
            printLines(" stderr:", processRun.getErrorStream());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


      }

      private static void printLines(String name, InputStream ins) throws Exception {
          String line = null;
          BufferedReader in = new BufferedReader(new InputStreamReader(ins));
          while ((line = in.readLine()) != null) {
              System.out.println(name + " " + line);
          }
        }
    }
🌐
CodingTechRoom
codingtechroom.com › question › run-java-program-from-another-java-program
How to Execute a Java Program from Another Java Program? - CodingTechRoom
Integrating legacy Java code that exists in the form of separate classes or applications. Use the `ProcessBuilder` class to configure and start a new process that executes the Java program you want. Utilize the `Runtime.exec()` method, though it's generally less flexible than `ProcessBuilder`.
Top answer
1 of 14
10

You're trying to execute "C:/". You'll want to execute something like:

"javaw.exe d:\\somejavaprogram\\program.jar"

Notice the path separators.

I'm assuming this is for an ad-hoc project, rather than something large. However, for best practice running external programs from code:

  • Don't hardcode the executable location, unless you're certain it will never change
  • Look up directories like %windir% using System.getenv
  • Don't assume programs like javaw.exe are in the search path: check them first, or allow the user to specify a location
  • Make sure you're taking spaces into account: "cmd /c start " + myProg will not work if myProg is "my program.jar".
2 of 14
8

You can either launch another JVM (as described in detail in other answers). But that is not a solution i would prefer.

Reasons are:

  • calling a native program from java is "dirty" (and sometimes crashes your own VM)
  • you need to know the path to the external JVM (modern JVMs don't set JAVA_HOME anymore)
  • you have no control on the other program

Main reason to do it anyway is, that the other application has no control over your part of the program either. And more importantly there's no trouble with unresponsive system threads like the AWT-Thread if the other application doesn't know its threading 101.

But! You can achieve more control and similar behaviour by using an elementary plugin technique. I.e. just call "a known interface method" the other application has to implement. (in this case the "main" method).

Only it's not quite as easy as it sounds to pull this off.

  • you have to dynamically include required jars at runtime (or include them in the classpath for your application)
  • you have to put the plugin in a sandbox that prevents compromising critical classes to the other application

And this calls for a customized classloader. But be warned - there are some well hidden pitfalls in implementing that. On the other hand it's a great exercise.

So, take your pick: either quick and dirty or hard but rewarding.

Top answer
1 of 3
30

I have modified the code to include some checks:

public class Laj {

  private static void printLines(String name, InputStream ins) throws Exception {
    String line = null;
    BufferedReader in = new BufferedReader(
        new InputStreamReader(ins));
    while ((line = in.readLine()) != null) {
        System.out.println(name + " " + line);
    }
  }

  private static void runProcess(String command) throws Exception {
    Process pro = Runtime.getRuntime().exec(command);
    printLines(command + " stdout:", pro.getInputStream());
    printLines(command + " stderr:", pro.getErrorStream());
    pro.waitFor();
    System.out.println(command + " exitValue() " + pro.exitValue());
  }

  public static void main(String[] args) {
    try {
      runProcess("javac Main.java");
      runProcess("java Main");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Here is the Main.java:

public class Main {
  public static void main(String[] args) {
    System.out.println("ok");
  }
}

When everything is fine, it just works:

alqualos@ubuntu:~/tmp$ java Laj
javac Main.java exitValue() 0
java Main stdout: ok
java Main exitValue() 0

Now, for example, if I have some error in Main.java:

alqualos@ubuntu:~/tmp$ java Laj
javac Main.java stderr: Main.java:3: package Systems does not exist
javac Main.java stderr:     Systems.out.println("ok");
javac Main.java stderr:            ^
javac Main.java stderr: 1 error
javac Main.java exitValue() 1
java Main stdout: ok
java Main exitValue() 0

It still prints "ok" because the previously compiled Main.class is still there, but at least you can see what exactly is happening when your processes are running.

2 of 3
0

You also need to

pro2.waitFor();

because executing that process will take some time and you can't take the exitValue() before the process has finished.

🌐
Coderanch
coderanch.com › t › 437074 › java › Running-java-program-java-program
Running java program from another java program (Java in General forum at Coderanch)
October 15, 2016 - If the resulting class from the ... clear the picture.. Normally if we are working in windows and not using any IDE then we do open a command promt, compile a java program then run it......
🌐
Stack Overflow
stackoverflow.com › questions › 36508827 › how-to-execute-a-java-program-from-another-java-program-in-eclipse
How to execute a java program from another java program in eclipse - Stack Overflow
Both programs are in the same package, I'm doing something like this: try{ System.out.println("Executing another client"); runProcess("javac -cp gridgain-examples C:/Users/Desktop/gridgain/examples/src/main/java/apache/ignite/schemas/Test.java"); System.out.println("******"); runProcess("java -cp gridgain-examples C:/Users/Desktop/gridgain/examples/src/main/java/apache/ignite/schemas/Test.java"); } catch(Exception e) { e.printStackTrace(); }
🌐
David Lim
davidlim2007.wordpress.com › 2016 › 12 › 22 › a-simple-java-program-to-run-another-java-program
A Simple Java Program To Run Another Java Program. – David Lim
December 22, 2016 - */ public class SimpleConsoleApp { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("Hello From StdOut."); System.err.println("Hello From StdErr."); } } This program simply prints 2 lines, one to the standard output stream and the other to the standard error. I am currently using NetBeans and so after compiling this simple test program, I get a SimpleConsoleApp.jar file in the Java project’s dist folder. I then copied the compiled JavaSimpleCommandLineAppLauncher.jar file to the dist folder. To run JavaSimpleCommandLineAppLauncher on SimpleConsoleApp.jar, we use the following command line :
🌐
IBM
ibm.com › docs › en › i › 7.4.0
Calling another Java program with java.lang.Runtime.exec()
October 7, 2025 - import java.io.*; public class CallHelloPgm { public static void main(String args[]) { Process theProcess = null; BufferedReader inStream = null; System.out.println("CallHelloPgm.main() invoked"); // call the Hello class try { theProcess = Runtime.getRuntime().exec("java QIBMHello"); } catch(IOException e) { System.err.println("Error on exec() method"); e.printStackTrace(); } // read from the called program's standard output stream try { inStream = new BufferedReader( new InputStreamReader( theProcess.getInputStream() )); System.out.println(inStream.readLine()); } catch(IOException e) { System.err.println("Error on inStream.readLine()"); e.printStackTrace(); } } }