Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用另一个Java程序编译Java程序,并使用Java编译器API打印输出?_Java - Fatal编程技术网

如何使用另一个Java程序编译Java程序,并使用Java编译器API打印输出?

如何使用另一个Java程序编译Java程序,并使用Java编译器API打印输出?,java,Java,我使用编译器API编写了一个简单的程序,并将包含简单Java程序的字符串存储到一个文件中,然后编译该文件。工作正常,现在我需要打印示例类生成的输出。我怎么做 String program="public class MyClass{ public static void main(String args[]) {System.out.println(\"My Method Called\");}}"; File newTextFile = new File("D:\\MyClass.jav

我使用编译器API编写了一个简单的程序,并将包含简单Java程序的字符串存储到一个文件中,然后编译该文件。工作正常,现在我需要打印示例类生成的输出。我怎么做

String program="public class MyClass{ public static void main(String args[])    {System.out.println(\"My Method Called\");}}";
File newTextFile = new File("D:\\MyClass.java");

FileWriter fw = new FileWriter(newTextFile);
fw.write(program);
fw.close();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
FileOutputStream err = new FileOutputStream("Error.txt");
      FileOutputStream out = new FileOutputStream("output.txt");  

int results = compiler.run(null,err,out,"newtextfile");
if(results== 0){

        System.out.println("Compilation is successful");

    }else{
        System.out.println("Compilation Failed");
    }

}
当编译成功时,它只打印结果。如何在编译的示例类中打印消息。请提供建议

现在,它创建输出和错误文件,但如果程序中有错误,则只有错误才会写入错误文件。如果程序编译时没有任何错误,则输出不会写入输出文件,将创建空文件。

是否需要

Process p = Runtime.getRuntime().exec("java my_class_file.class");
/* running compiled code in a separated process */
InputStream in = p.getInputStream();
InputStream err = p.getErrorStream();
OutputStream out = p.getOutputStream();
/* in,err and out streams */
// Return compilation log!
public String compile(String compilationCommand){     
Process p = null;
try {
    p = Runtime.getRuntime().exec(compilationCommand);
    p.waitFor();
} catch (IOException e) {

} catch (InterruptedException e) {

}

Scanner scanner = new Scanner(p.getInputStream());
String result = null;

try{
    result = scanner.useDelimiter("$$").next();
} catch (NoSuchElementException e) {

}
scanner.close();

if(result != null)
   return "Compilation is successful";
else
  return "Compilation Failed\n" + result;
}

下面是一个例子:-您需要设置output.class文件并使用类加载器加载新类。这个例子看起来很好:嗨,有没有办法随机编译文件列表以生成类文件?请给出建议