Taketheword
Taketheword

Reputation: 1

Run another Java program from within a Java program and get outputs/send inputs

I need a way to run another java application from within my application. I want to recive its outputs into a JTextArea and send it inputs via a JTextBox.

Upvotes: 0

Views: 3053

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

Depends.

You could use a custom URLClassLoader to load the second applications jar and call the main classes main method directly. Obviously, the issue there is getting the output from the program ;)

The other solution would be to use a ProcessBuilder to launch a java process and read the output via the InputStream

The problem here is trying to find the java executable. In general, if it's in the path you should be fine.

You can have a look at this as a base line example of how to read the inputstream

UPDATED with Example

This is my "output" program that produces the output...

public class Output {
    public static void main(String[] args) {
        System.out.println("This is a simple test");
        System.out.println("If you can read this");
        System.out.println("Then you are to close");
    }
}

This is my "reader" program that reads the input...

public class Input {

    public static void main(String[] args) {

        // SPECIAL NOTE
        // The last parameter is the Java program you want to execute
        // Because my program is wrapped up in a jar, I'm executing the Jar
        // the command line is different for executing plain class files
        ProcessBuilder pb = new ProcessBuilder("java", "-jar", "../Output/dist/Output.jar");
        pb.redirectErrorStream();

        InputStream is = null;
        try {

            Process process = pb.start();
            is = process.getInputStream();

            int value;
            while ((value = is.read()) != -1) {

                char inChar = (char)value;
                System.out.print(inChar);

            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }        
    }
}

You can also checkout Basic I/O for more information

Upvotes: 3

Related Questions