【问题标题】:how to get the output of a java program?如何获取java程序的输出?
【发布时间】:2014-09-30 09:23:25
【问题描述】:

我需要编写一个代码来帮助我获得程序的输出。

我正在编译的那个 Java 文件 MainClass.java 中有一个打印 "OK" 的简单代码。

我怎样才能返回这个输出,即使有错误,我也需要接受它。

这是我编译和创建.class 文件的代码。

File sourceFile = new File("C:\\Projet_Interne\\webProject\\NewFolder\\MainClass.java");  
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null,sourceFile.getPath());
int result = compiler.run(System.in,System.out,System.err,sourceFile.getPath());
     System.out.println("Compile result code = " + result);
      if(compilationResult == 0){
            System.out.println("Compilation is successful");
      }else{
             System.out.println("Compilation Failed");
      }
 StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);
 stdFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("C:\\Projet_Interne\\webProject\\NewFolder")));

【问题讨论】:

  • 您需要运行生成的代码,对于exampleexample,使用ClassLoaderProcessBuilder
  • 当您编译源代码时,如果发生错误,它会在控制台上打印。如果你得到了最终的类文件,程序就可以运行了

标签: java compiler-construction


【解决方案1】:

您可以使用DiagnosticCollector,它可以让您收集有关编译过程的诊断信息,您可以从JavaDocs找到更多详细信息

例如...

File helloWorldJava = new File(...);

DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

// This sets up the class path that the compiler will use.
// I've added the .jar file that contains the DoStuff interface within in it...
List<String> optionList = new ArrayList<String>();
optionList.add("-classpath");
optionList.add(System.getProperty("java.class.path"));

Iterable<? extends JavaFileObject> compilationUnit
        = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
JavaCompiler.CompilationTask task = compiler.getTask(
    null, 
    fileManager, 
    diagnostics, 
    optionList, 
    null, 
    compilationUnit);
if (task.call()) {
    System.out.println("Yipe");
} else {
    // Opps compile failed...
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
        System.out.format("Error on line %d in %s%n",
                diagnostic.getLineNumber(),
                diagnostic.getSource().toUri());
    }
}
fileManager.close();

编译后,您有两个选择,您可以使用自定义类加载器来加载类并执行它,这将使用您当前的标准输出...

// Create a new custom class loader, pointing to the directory that contains the compiled
// classes, this should point to the top of the package structure!
URLClassLoader classLoader = new URLClassLoader(new URL[]{new File("./").toURI().toURL()});
// Load the class from the classloader by name....
Class<?> loadedClass = classLoader.loadClass("testcompile.HelloWorld");
// Create a new instance...
Object obj = loadedClass.newInstance();
// Santity check
if (obj instanceof DoStuff) {
    // Cast to the DoStuff interface
    DoStuff stuffToDo = (DoStuff)obj;
    // Run it baby
    stuffToDo.doStuff();
}

或者使用ProcessBuilder 来执行另一个Java 进程...

ProcessBuilder pb = new ProcessBuilder("java", "HelloWorld");
pb.directory(new File("src"));
pb.redirectError();
Process p = pb.start();

InputStreamConsumer.consume(p.getInputStream());

p.waitFor();

供参考,InputStreamConsumer....

public static class InputStreamConsumer implements Runnable {

    private InputStream is;

    public InputStreamConsumer(InputStream is) {
        this.is = is;
    }

    public InputStream getInputStream() {
        return is;
    }

    public static void consume(InputStream is) {
        InputStreamConsumer consumer = new InputStreamConsumer(is);
        Thread t = new Thread(consumer);
        t.start();
    }

    @Override
    public void run() {
        InputStream is = getInputStream();
        int in = -1;
        try {
            while ((in = is.read()) != -1) {
                System.out.print((char)in);
            }
        } catch (IOException exp) {
            exp.printStackTrace();
        }
    }

}

这在以下有更详细的概述:

【讨论】:

  • 谢谢你的回答,即使它是一个漫长的过程,但它可以完成工作:)
  • @Neeldz 很多选项:P
【解决方案2】:

run 方法可以使用流来处理输入和输出:

int run(InputStream in,
      OutputStream out,
      OutputStream err,
      String... arguments)

out 使用OutputStream,并在run 完成时读取它。

【讨论】:

  • 这似乎是 OP 正在做的事情...int result = compiler.run(System.in,System.out,System.err,sourceFile.getPath());,还是他们做错了?
  • thx Tichodroma 为你的回复我已经使用了这个方法如下但是那个函数只返回一个 int 值我需要得到编译类的返回希望在这种情况下是“OK”。@987654328 @
猜你喜欢
  • 1970-01-01
  • 2012-03-06
  • 2023-03-10
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 2020-02-22
相关资源
最近更新 更多