这是我所做的:-
// compile
Runtime.getRuntime().exec("javac C:\\dir1\\dir2\\dir3\\Main.java");
// run
Runtime.getRuntime().exec("java C:\\dir1\\dir2\\dir3\\Main");
我能够成功编译该文件,但无法运行它。在使用 exec("java Main")
之前,我尝试过使用 exec("cd C:\\dir1\\dir2\\dir3")
但没有任何好处。有什么想法吗?
最佳答案
使用ProcessBuilder
。与在现代代码中根本不应该使用的 Runtime.exec() 不同,ProcessBuilder 允许您设置生成的进程将在其中运行的目录。 Runtime.exec()
不会为您提供此选项。
因此:
final Path basePath = Paths.get("C:\\dir1\\dir2\\dir3");
final Process compileProcess = new ProcessBuilder("javac", "Main.java")
.directory(basePath.toFile())
// other niceties of ProcessBuilder
.start();
// check the status of the process; rinse, repeat
关于java - 使用 Java 运行时编译/运行 .java 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22102150/