本文介绍了从另一个Java程序编译和运行Java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用CompileAndRun类,我现在可以编译并运行我的HelloWorld类。
现在我想用它来运行一个需要用户输入的程序。这可以是命令行参数或通过stdin接收的输入。

using the CompileAndRun class, i can now compile and run my HelloWorld class.now i want to use this to run a program that requires users input. this may either be a command line argument or input received through stdin.

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class CompileAndRun {

public static void main(String[] args) {
    new CompileAndRun();
}

public CompileAndRun() {
    try {
        int result = compile("compileandrun/HelloWorld.java");
        System.out.println("javac returned " + result);
        result = run("compileandrun.HelloWorld");
    } catch (IOException | InterruptedException ex) {
        ex.printStackTrace();
    }
}

public int run(String clazz) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder("java", clazz);
    pb.redirectError();
    pb.directory(new File("src"));
    Process p = pb.start();
    InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
    consumer.start();

    int result = p.waitFor();

    consumer.join();

    System.out.println(consumer.getOutput());

    return result;
}

public int compile(String file) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder("javac", file);
    pb.redirectError();
    pb.directory(new File("src"));
    Process p = pb.start();
    InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
    consumer.start();

    int result = p.waitFor();

    consumer.join();

    System.out.println(consumer.getOutput());

    return result;
}

public class InputStreamConsumer extends Thread {

    private InputStream is;
    private IOException exp;
    private StringBuilder output;

    public InputStreamConsumer(InputStream is) {
        this.is = is;
    }

    @Override
    public void run() {
        int in = -1;
        output = new StringBuilder(64);
        try {
            while ((in = is.read()) != -1) {
                output.append((char) in);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            exp = ex;
        }
    }

    public StringBuilder getOutput() {
        return output;
    }

    public IOException getException() {
        return exp;
    }
}
}


推荐答案

在我看来,更好的解决方案是使用。您应该查看也是。

In my opinion better solution is use of the Java 6 Compiler API. You should look at javax.tools package documentation too.

这篇关于从另一个Java程序编译和运行Java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 03:59