tôi đã nhận mã Java này từ một chủ đề Stack OverflowLập trình biên dịch java bằng JavaCompiler?
import java.io.*;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class Main {
public static void main(String[] args) throws IOException{
String source = " public class Test { public static void main(String args[]) { System.out.println(\"hello\"); } }";
// Save source in .java file.
File root = new File("C:\\java\\");
root.mkdir();
File sourceFile = new File(root, "\\Test.java");
Writer writer = new FileWriter(sourceFile);
writer.write(source);
writer.close();
// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());
}
}
Nhưng tôi tiếp tục nhận một NullPointerException như thế này
Exception in thread "main" java.lang.NullPointerException
at com.zove.compiler.Main.main(Main.java:24)
Nó không biên dịch nhưng nó ném ngoại lệ khi chạy. Tôi đang làm gì sai?
Dòng nào là 'Main.java: 24'? 'ToolProvider.getSystemJavaCompiler()' có trả về null không? – mpartel
Với mã chỉ dài 21 dòng, tôi không thể thấy NPE có thể xảy ra ở dòng 24. Có phải ý định của bạn là lãng phí thời gian của những người đang cố gắng giúp bạn? Bạn đang ** sử dụng mã nào? –
@AndrewThompson Bạn có thể xem qua câu hỏi này không? http://stackoverflow.com/questions/36583278/how-can-compile-i-java-file-in-jsp – sony