-4

Possible Duplicate:
how to compile & run java program in another java program?

eg if i have A.java and B.java then i want to compile and run B.java using A.java.

Community
  • 1
  • 1
user1722639
  • 1
  • 1
  • 1
  • 1

2 Answers2

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.

AlexR
  • 114,158
  • 16
  • 130
  • 208
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);
          }
        }
    }