2012-07-21 231 views
1

我的程序要求我运行一个.bat文件,它将编译java源代码。这运行良好,但我正在寻找一个解决方案,它将获得compile.bat的输出(和可能的错误)并将其添加到GUI上的文本窗格中。我有下面的代码,但是当执行过程发生时不打印任何内容到窗格并且没有任何错误。如何从.bat进程获取输出以显示在JTextPane中?

GenerationDebugWindow.main(null); 

Process process = rut.exec(new String[] {file.getAbsolutePath() + "\\compile.bat"}); 
Scanner input = new Scanner(process.getInputStream()); 

InputStream is = process.getInputStream(); 
InputStreamReader isr = new InputStreamReader(is); 
BufferedReader reader = new BufferedReader(isr); 

String line; 
int exit = -1; 

while ((line = reader.readLine()) != null) { 
    // Outputs your process execution 
    try { 
     exit = process.exitValue(); 
     GenerationDebugWindow.writeToPane(line); 
     System.out.println(line); 
     if (exit == 0) { 
      GenerationDebugWindow.writeToPane("Compilation Finished!"); 
      if(new File(file + "/mod_" + WindowMain.modName.getText()).exists()){ 
       GenerationDebugWindow.writeToPane("Compilation May Have Experienced Errors."); 
      } 
     } 
    } catch (IllegalThreadStateException t) { 

    } 
} 

GenerationDebugWindow

private static JTextPane outputPane; 
public static void writeToPane(String i){ 
    outputPane.setText(outputPane.getText() + i + "\r\n"); 
} 
+3

你_read_为'Process.exitValue的javadoc()'将来电转接到您的代码,或只是坚持catch块在你的代码,因为IDE叫你过吗? – jtahlborn 2012-07-21 00:41:50

回答

2

用途:

Runtime.getRuntime().exec("cmd.exe /C " + file.getAbsolutePath() + "\\compile.bat"); 
+0

很好的调用cmd.exe/C – Matt 2012-07-21 00:47:57

1

参考这个问题:Java Process with Input/Output Stream

这可能是因为该过程的输出将错误流。但是,ProcessBuilder是一个比直接使用System.getRuntime()更有用的类。exec()

在下面的示例中,我们告诉ProcessBuilder将错误流重定向到输出流的相同流,这简化了代码。

ProcessBuilder builder = new ProcessBuilder("cmd.exe /C " + file.getAbsolutePath() + "\\compile.bat"); 
builder.redirectErrorStream(true); 
builder.directory(executionDirectory); // if you want to run from a specific directory 
Process process = builder.start(); 
Reader reader = ...; 
String line = null; 
while ((line = reader.readLine()) != null) { 
    System.out.println ("Stdout: " + line); 
} 

int exitValue = process.exitValue(); 
0

我的程序要求我运行.bat文件,将编译Java源代码。

您在* nix和OS X上的用户需要使用JavaCompiler编译源代码。

STBC是使用JavaCompiler的示例。它是open source。它使用JTextArea而不是JTextPane来保存源代码和错误,但应该很容易适应。

Compilation error Compiled successfully