我正在做我的第一个Java项目,即一个TextEditor,它也可以编译和运行文件。编译器(javax.tools.JavaCompiler)正常工作,但是当我尝试运行“ .class”文件时,没有任何显示。我需要帮助。
以下是编译代码:
public void compileIt(String s) //s is the absolute path of file to be compiled
{
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
MyDiagnosticListener listener = new MyDiagnosticListener();
StandardJavaFileManager fileManager =
compiler.getStandardFileManager(listener, null, null);
File file;
file = new File(s);
String classOutputFolder ="E:\\codefiles"; //destination for storing .class files
Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(file);
Iterable options = Arrays.asList("-d", classOutputFolder);
JavaCompiler.CompilationTask task =
compiler.getTask(null, fileManager, listener, options, null, javaFileObjects);
if (task.call()) {
System.out.println("compilation done");
}
try {
fileManager.close();
} catch (IOException ex) {
Logger.getLogger(getName()).log(Level.SEVERE, null, ex);
}
}
用于运行.class文件的代码:
void runIt()
{
String s = null;
try {
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("java -cp E:\\codefiles");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
while ((s = stdInput.readLine()) != null) {
System.out.println("output is working:\n");
System.out.println(s);
}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
catch (IOException ex1) {
ex1.printStackTrace();
}
}
答案 0 :(得分:0)
一个原因
Process p = Runtime.getRuntime().exec("java -cp E:\\codefiles");
不起作用是因为命令行语法错误。您还需要提供一个类名。例如
Process p = Runtime.getRuntime().exec(
"java -cp E:\\codefiles com.example.MyMain");
这假定您要运行的类具有合适的main
方法。