【发布时间】:2017-05-03 10:20:59
【问题描述】:
我正在编写一个程序,该程序使用 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!\n");
}
/**
* 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
这里应该是什么问题?
【问题讨论】:
-
尝试将文件作为
Main.java而不是./Main.java传递。