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測試成功!"); } } 編譯成功的輸出結果: