Chang Sun
Chang Sun

Reputation: 31

How to call a Java class from Java code using Runtime exec

I would like to know if there is a way to call a Java class from another. I implemented a testing code as follows using Runtime exec, calling "test.java" from "exec.java", but the exec calling won't execute. What is the problem in the code? Thanks.

test.java:

package com.example.exec;

public class test{

    public static void main(String args[]) {
        System.out.println("Hello World!");
    }
}

exec.java:

package com.example.exec;

public class exec {

    public static void main(String args[]) {
        try {
            Process pro = Runtime.getRuntime().exec("java test");
        } catch (Exception err) {
            System.out.println("Error!");
        }
    }
}

Upvotes: 3

Views: 1551

Answers (2)

Ali Helmy
Ali Helmy

Reputation: 794

So you need first to compile the Java class from .java to .class:

 Process pro = Runtime.getRuntime().exec("javac -d . com/example/exec/test");

then execute the .class

 pro = Runtime.getRuntime().exec("java com/example/exec/test");

Then read the input stream from the process

Upvotes: 0

that other guy
that other guy

Reputation: 123410

If you want to run an arbitrary java class using Runtime.exec, you need a valid java command and to relay any output:

$ cat com/example/exec/exec.java
package com.example.exec;

public class exec {
  public static void main(String args[]) {
    try {
      Process pro = Runtime.getRuntime().exec("java com.example.exec.test");
      byte[] buffer = new byte[65536];
      int length;
      while((length = pro.getInputStream().read(buffer, 0, buffer.length)) != -1) {
        System.out.write(buffer, 0, length);
      }
    } catch (Exception err) {
      System.out.println("Error!");
      err.printStackTrace();
    }
  }
}

This should only ever be used by IDEs, build tools and similar. Java classes in the same program should never use Runtime.exec to invoke or communicate with each other.

Upvotes: 3

Related Questions