0

I want my java program to execute a different java program. I used following method.

(The program I want to run is Example.java)

class RunJava
{
public static void main(String a[])throws Exception
{
Runtime.getRunTime().exec("c:\\"+path+"\\javac Example.java");
Runtime.getRunTime().exec("c:\\"+path+"\\java Example");
}

But it is not working. Is there any other way of doing this?

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • 2
    `javac` should be the first.. before that path (and `java` too). – Maroun Jan 01 '14 at 11:58
  • its not the classpath. It is path of where javac is located in the system – user2916888 Jan 01 '14 at 11:59
  • 2
    If the 2nd app. is on the run-time class-path of the first, it is both simpler and cleaner to just create an instance of it, or directly call the `main(String[])`.. Read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html). That might solve the problem. If not, it should provide more information as to the reason it failed. Then ignore that it refers to `exec` and build the `Process` using a `ProcessBuilder`. Also break a `String arg` into `String[] args` to account for arguments which themselves contain spaces. – Andrew Thompson Jan 01 '14 at 12:00

2 Answers2

1

please refer how to compile & run java program in another java program?. Same solution available !!

Community
  • 1
  • 1
Jamsheer
  • 3,673
  • 3
  • 29
  • 57
  • It works fine, but I'm unable to understand how to give input to the 2nd program. And I am unable to post comment on the link you suggested. So could you answer this too? – user2916888 Jan 01 '14 at 12:53
0

Why don't you create an executable jar for the Example.java and place it in the path then execute it with:

Runtime.getRunTime().exec("c:/"+path+"/java -jar Example.jar");
karimyafi
  • 494
  • 2
  • 5
  • 14