如何使用其他Java程序编译Java程序并使用Java编译器API打印输出?

时间:2013-12-27 14:39:00

标签: java

我使用编译器API编写了一个简单的程序,并将包含简单Java程序的字符串存储到文件中并编译该文件。它的工作正常,现在我需要打印样本类生成的输出。我该怎么办?

String program="public class MyClass{ public static void main(String args[])    {System.out.println(\"My Method Called\");}}";
File newTextFile = new File("D:\\MyClass.java");

FileWriter fw = new FileWriter(newTextFile);
fw.write(program);
fw.close();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
FileOutputStream err = new FileOutputStream("Error.txt");
      FileOutputStream out = new FileOutputStream("output.txt");  

int results = compiler.run(null,err,out,"newtextfile");
if(results== 0){

        System.out.println("Compilation is successful");

    }else{
        System.out.println("Compilation Failed");
    }

}

仅在编译成功时打印结果。如何在编译的示例类中打印消息。请提供建议。

现在它创建输出和错误文件但是如果程序中有任何错误,只会在错误文件中写入错误。如果程序编译没有任何错误,则输出不会写入输出文件,会创建空文件。

2 个答案:

答案 0 :(得分:0)

Process p = Runtime.getRuntime().exec("java my_class_file.class");
/* running compiled code in a separated process */
InputStream in = p.getInputStream();
InputStream err = p.getErrorStream();
OutputStream out = p.getOutputStream();
/* in,err and out streams */

答案 1 :(得分:0)

你需要吗?

// Return compilation log!
public String compile(String compilationCommand){     
Process p = null;
try {
    p = Runtime.getRuntime().exec(compilationCommand);
    p.waitFor();
} catch (IOException e) {

} catch (InterruptedException e) {

}

Scanner scanner = new Scanner(p.getInputStream());
String result = null;

try{
    result = scanner.useDelimiter("$$").next();
} catch (NoSuchElementException e) {

}
scanner.close();

if(result != null)
   return "Compilation is successful";
else
  return "Compilation Failed\n" + result;
}