2

I want to make a program that open another java programs.how can i run/execute the cmd command in compiling and running java programs.

for example c:\Users\Burnok> javac HelloWorld.java and c:\Users\Burnok> java HelloWorld

how can i do that inside the java program? please help.

I tried this code but it compiled successfully but if i tried to run the HelloWorld.class it says that the could not find or load main class.

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

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;


public class Test {

     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();
      }

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

}

here is the error java src/HelloWorld stderr: Error: Could not find or load main class src.HelloWorld

user3276091
  • 263
  • 3
  • 10

1 Answers1

1

Your are supposed to mention class path while running from another directory

syntax is java -classpath directory_to_program Program

try {
        runProcess("javac src/HelloWorld.java");
        runProcess("java -classpath src HelloWorld");
    } catch (Exception e) {
      e.printStackTrace();
    }

Read for more info How do I run a java program from a different directory?

Community
  • 1
  • 1
sujithvm
  • 2,351
  • 3
  • 15
  • 16