简体   繁体   English

从Java程序中运行另一个Java程序并获取输出/发送输入

[英]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. 我需要一种方法从我的应用程序中运行另一个Java应用程序。 I want to recive its outputs into a JTextArea and send it inputs via a JTextBox. 我想将其输出重新放入JTextArea并通过JTextBox发送输入。

Depends. 要看。

You could use a custom URLClassLoader to load the second applications jar and call the main classes main method directly. 您可以使用自定义URLClassLoader来加载第二个应用程序jar并直接调用main类main方法。 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 另一种解决方案是使用ProcessBuilder启动java进程并通过InputStream读取输出

The problem here is trying to find the java executable. 这里的问题是试图找到java可执行文件。 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 你可以看看是如何阅读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 您还可以查看基本I / O以获取更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM