-3

Possible Duplicate:
Execute a Java program from our Java program

I wanted to execute another java program from our java program. When i run a java program called 'First.java', it should prompt the user to enter the name of any class name(.java file name) and then it should read that input(.java file) and should be able to compile and run that program.Can anyone give me a sample code for that?

Community
  • 1
  • 1
Venkata
  • 31
  • 2
  • 7
  • you need to be a bit more specific, can you post part or all of both Java programs? And then show us where you want to call the other Java program – Hunter McMillen Oct 14 '11 at 15:44
  • What do you mean by `execute`? Do you want the program to start up in its own JVM as if it was launched from the command line? Do you just want to execute a part of the code from your own program? Do you want to have the program running as a separate process in your current program's JVM? – John B Oct 14 '11 at 15:48
  • @JohnB Yes, i wanted the program to start as if it was launched from the command line. – Venkata Oct 14 '11 at 16:04

3 Answers3

4

It isn't clear from the question, but I will assume the other Java program is a command line program.

If this is the case you would use Runtime.exec().

It isn't quite that simple if you want to see what the output of that program is. Below is how you would use Runtime.exec() with any external program, not just a Java program.

First you need a non-blocking way to read from Standard.out and Standard.err

private class ProcessResultReader extends Thread
{
    final InputStream is;
    final String type;
    final StringBuilder sb;

    ProcessResultReader(@Nonnull final InputStream is, @Nonnull String type)
    {
        this.is = is;
        this.type = type;
        this.sb = new StringBuilder();
    }

    public void run()
    {
        try
        {
            final InputStreamReader isr = new InputStreamReader(is);
            final BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null)
            {
                this.sb.append(line).append("\n");
            }
        }
        catch (final IOException ioe)
        {
            System.err.println(ioe.getMessage());
            throw new RuntimeException(ioe);
        }
    }

    @Override
    public String toString()
    {
        return this.sb.toString();
    }
}

Then you need to tie this class into the respective InputStream and OutputStreamobjects.

    try
    {
        final Process p = Runtime.getRuntime().exec(String.format("cmd /c %s", query));
        final ProcessResultReader stderr = new ProcessResultReader(p.getErrorStream(), "STDERR");
        final ProcessResultReader stdout = new ProcessResultReader(p.getInputStream(), "STDOUT");
        stderr.start();
        stdout.start();
        final int exitValue = p.waitFor();
        if (exitValue == 0)
        {
            System.out.print(stdout.toString());
        }
        else
        {
            System.err.print(stderr.toString());
        }
    }
    catch (final IOException e)
    {
        throw new RuntimeException(e);
    }
    catch (final InterruptedException e)
    {
        throw new RuntimeException(e);
    }

This is pretty much the boiler plate I use when I need to Runtime.exec() anything in Java.

A more advanced way would be to use FutureTask and Callable or at least Runnable rather than directly extending Thread which isn't the best practice.

NOTE:

The @Nonnull annotations are in the JSR305 library. If you are using Maven, and you are using Maven aren't you, just add this dependency to your pom.xml.

<dependency>
  <groupId>com.google.code.findbugs</groupId>
  <artifactId>jsr305</artifactId>
  <version>1.3.9</version>
</dependency>
2
  • Call the other program's main method (or whatever is the entry point in the other program)

  • or use ProcessBuilder

michael667
  • 3,241
  • 24
  • 32
  • +1 The second program is a Java program, and the poster's description shows no reason `SecondProgramClass.main(...)` couldn't be invoked programmatically. – spork Oct 14 '11 at 15:49
  • It would most likely be more efficient to call the other program's main method as then there's no need to create a new process, which is relatively expensive. I suppose there might be issues of collisions between the two apps, like if they had classes with the same name. – Jay Oct 14 '11 at 16:06
-1

if the other java program is an executable program,you can just use code like this:

    try 
    { 
    Runtime.getRuntime().exec("C:\\my.exe"); 
    }
catch(IOException ex) 
    { } 
deskmore
  • 518
  • 4
  • 3
  • I prefer `ProcessBuilder` over `Runtime.exec` because its API is easier to use – michael667 Oct 14 '11 at 15:48
  • 3
    -1 a poor answer (both in process & execution) to a poorly asked question. Don't try this at home, kids (and if you do, put a great deal more effort into writing it)! – Andrew Thompson Oct 14 '11 at 16:05
  • **this is the most outdated ( and incorrect ) answer on this question! Do not follow this answer! Look below for current idiomatic ways to do this!** –  Jul 25 '17 at 15:39