我正在编写一个程序,其中包含一个功能,用户可以在文本框中输入 Java 代码并能够编译和运行它。我得到的错误是:
顶部显示的两个目录是正确的,并且当我从同一工作目录通过命令提示符手动执行该命令时,该命令有效。我使用的是 Windows 10,代码如下:
public Process compile() throws IOException {
save(); //saves changes to source file
System.out.println(file.getCanonicalPath());
ProcessBuilder processBuilder = new ProcessBuilder("javac", file.getCanonicalPath());
processBuilder.directory(new File(settingsFile.getJdkPath()));
System.out.println(processBuilder.directory());
Process process = processBuilder.start(); //Throws exception
this.compiledFile = new File(file.getParentFile(), file.getName().replace(".java", ".class"));
return process;
}
最佳答案
使用此代码,我能够将 Test.java 文件编译为桌面上的 Test.class 文件。
import java.io.IOException;
public class App {
public static Process compile() throws IOException {
String myFilePath = "C:\\Users\\redacted\\Desktop\\Test.java";
String javacPath = "C:\\Program Files\\Java\\jdk1.8.0_171\\bin\\javac.exe";
ProcessBuilder processBuilder = new ProcessBuilder(javacPath, myFilePath);
return processBuilder.start();
}
public static void main(String[] args) throws IOException {
Process process = compile();
}
}
使用String javacPath = "javac.exe";
也有效,但这可能是因为我的 JDK bin 位于我的 PATH 变量中。
ProcessBuilder 构造函数调用中的路径或权限有问题。
关于java - 命令可以通过命令行运行,但在使用 ProcessBuilder 时不能运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53583487/