int run(InputStream in, OutputStream out, OutputStream err, String... arguments) 假如前3个参数传入的是null,那么run方法将以标准的输入、输出代替,即System.in、System.out和System.err。假如我们要编译一个test.java文件,并将使用标准输入输出,run的使用方法如下:
int results = tool.run(null, null, null, "test.java"); 下面是使用JavaCompiler的完整代码:
import java.io.*; import javax.tools.*;
public class test_compilerapi { public static void main(String args[]) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int results = compiler.run(null, null, null, "test.java"); System.out.println((results == 0)?"编译成功":"编译失败"); // 在程序中运行test Runtime run = Runtime.getRuntime(); Process p = run.exec("java test"); BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; while ((s = br.readLine()) != null) System.out.println(s); } }
public class test { public static void main(String[] args) throws Exception { System.out.println("JavaCompiler测试成功!"); } } 编译成功的输出结果: