0

我需要一种从我的应用程序中运行另一个 java 应用程序的方法。我想将其输出接收到 JTextArea 并通过 JTextBox 发送输入。

4

1 回答 1

3

要看。

您可以使用自定义URLClassLoader加载第二个应用程序 jar 并直接调用主类main方法。显然,问题在于从程序中获取输出;)

另一种解决方案是使用 aProcessBuilder启动 java 进程并通过InputStream

这里的问题是试图找到 java 可执行文件。一般来说,如果它在路径中,你应该没问题。

您可以将其视为如何读取输入流的基线示例

更新示例

这是我的“输出”程序,它产生输出......

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");
    }
}

这是我的“阅读器”程序,它读取输入......

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();
        }        
    }
}

您还可以查看基本 I/O以获取更多信息

于 2012-10-13T01:45:41.467 回答