Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a Java program from our Java program

Tags:

java

I used

Runtime.getRuntime().exec("_____")

but it throws a IOException as below:

java.io.IOException: CreateProcess: c:/ error=5
  at java.lang.Win32Process.create(Native Method)
  at java.lang.Win32Process.<init>(Win32Process.java:63)
  at java.lang.Runtime.execInternal(Native Method

I don't know whether I have the problem with specifying the path or something else. Can anyone please help me with the code.

like image 658
Arun Avatar asked Feb 02 '09 08:02

Arun


People also ask

How do you call a Java program from another Java program?

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. We will use the same approach to compile and run a java program from another java program.

Which file is used to execute a Java program?

We run the . class file to execute the Java programs.


1 Answers

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.

like image 147
Stroboskop Avatar answered Oct 24 '22 19:10

Stroboskop