我正在编写一个程序,它使用main方法获取输入".java"文件的路径。 然后程序应该编译该文件并运行它。
假设我正在尝试编译和运行的程序如下所示:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
执行编译并尝试运行它的程序:
Evaluator.java
/**
* Matches any .java file.
*/
private static final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.java");
private static String path;
/**
* Program entry point. Obtains the path to the .java file as a command line argument.
*
* @param args One argument from the command line: path to the .java file.
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if (args.length != 1) {
throw new IllegalArgumentException(
"Expected exactly one argument from the command line.");
}
if (!matcher.matches(Paths.get(args[0]))) {
throw new IllegalArgumentException(
String.format("File %s is not a valid java file.", args[0]));
}
// path is in a valid format
path = args[0];
// compile a program
compile();
// run a program
run();
}
/**
* Compiles a program.
*
* @throws Exception
*/
private static void compile() throws Exception {
System.out.println("Compiling the program ...");
Process p = Runtime.getRuntime().exec("javac" + path);
output("Std.In", p.getInputStream());
output("Std.Out", p.getErrorStream());
p.waitFor();
System.out.println("Program successfully compiled!
");
}
/**
* Runs a program.
*
* @throws Exception
*/
private static void run() throws Exception {
System.out.println("Executing the program ...");
Process p = Runtime.getRuntime().exec("java" + getProgramName(path));
output("Std.In", p.getInputStream());
output("Std.Out", p.getErrorStream());
p.waitFor();
System.out.println("Program finished!");
}
private static void output(String stream, InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, CS));
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
System.out.println(String.format("%s: %s", stream, line));
}
}
private static String getProgramName(String path) {
return path.replace(".java","");
}
}
我的"Main.java"文件位于项目根目录中。 我正在使用命令行参数"./Main.java"运行该程序。 这样做,正确编译程序并生成一个新文件"Main.class"。 但是,run方法输出如下:
Std.Out:错误:无法找到或加载主类..主
这应该是什么问题?
尝试将文件作为Main.java而不是./Main.java传递。
尝试设置java进程,启动正确的工作目录,然后设置相关的类路径。
这应该有所帮助。
更新
我建议使用方法Runtime.getRuntime().exec(String command, String[] envp, File dir)。
最后一个参数dir是进程工作目录。
你能提供一个如何做到这一点的例子吗?
@wesleyy我已经更新了我的答案
看看这个stackoverflow.com/questions/6811522/
这里的问题是你正在传递论点
./Main.java
相反,您应该将Main.java作为参数传递,否则您需要更改getProgramName()方法以正确返回类名。
这将允许您使用javac命令完美地编译程序,但是当您需要运行程序时会出现问题,因为该命令应该是
java Main
而你正试图执行
java ./Main
但你必须给它一个程序的路径,对吧? 如果程序不在项目根目录中,例如在"./data/Main.java"中,该怎么办? 那么运行命令应该怎么做?
是的,但您需要更改getProgramName()方法以返回正确的类名
如果编译的文件是"./data/Main.class",会发生什么? 那你如何执行该程序? 应该有所不同,不是吗?
在这种情况下,您需要使用-cp标志来提供正确的类路径,然后使用类名java -cp ../somepath../ Main
无论是什么人投票,都要做出评论,以便我可以改进答案或将其删除。 如果答案不合适。 但要注意评论