如何使用java代码对"另一段java代码"进行编译和运行呢?
下文笔者讲述java代码对另一段java代码进行编译和运行的方法分享,如下所示:
实现思路:
借助Runtime.getRuntime().exec()方法即可实现 编译和运行java文件的效果
例:
public class TestClass {
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
public static void main(String[] args) {
try {
runProcess("javac Test2.java");
runProcess("java Main");
} catch (Exception e) {
e.printStackTrace();
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


