如何在程序中运行java源代码。
可能重复:如何在程序中运行java源代码。,java,Java,可能重复: 我们小组希望在java程序/应用程序中运行java源代码,因为其中的语法是无错误的。这怎么可能?我们还需要编译错误吗?还是编译不可避免?谢谢你 就像netbeans可以在下面运行代码一样。您可以使用这个函数java.lang.Runtime.exec(),这是另一个关于如何执行的函数,以及如何读取命令的输出和执行过程中可能出现的错误: import java.io.*; public class JavaRunCommand { public static void m
我们小组希望在java程序/应用程序中运行java源代码,因为其中的语法是无错误的。这怎么可能?我们还需要编译错误吗?还是编译不可避免?谢谢你
就像netbeans可以在下面运行代码一样。您可以使用这个函数java.lang.Runtime.exec(),这是另一个关于如何执行的函数,以及如何读取命令的输出和执行过程中可能出现的错误:
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
// run the Unix "ps -ef" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("ps -ef");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
更多详细信息:听起来像python:D中的
eval()
。顺便说一句,请查看这个答案:这个问题已经在上面的链接中得到了回答