Note that there are some explanatory texts on larger screens.

plurals
  1. PORedirect a system call output to a file with Java
    text
    copied!<p>Currently having troubles to redirect the output of a small windows batch console to a log file. My Java application needs to start the Runtime.exec() call without waiting it to finish and still log the output. Here is my logger class : </p> <pre><code>public class BatchThreadLogger extends Thread { private Process process; private String logFilePath; private static final Logger logger = Logger.getLogger(BatchThreadLogger.class); public BatchThreadLogger(Process process, String logFilePath) { this.process = process; this.logFilePath = logFilePath; } public void run() { try { // create logging file File file = new File(logFilePath); file.createNewFile(); // create a writer object OutputStream os = new FileOutputStream(file); PrintWriter pw = new PrintWriter(os); // catch the process output in an InputStream InputStreamReader isr = new InputStreamReader(process.getInputStream()); BufferedReader br = new BufferedReader(isr); // wait for the process to complete int processStatus = process.waitFor(); // redirect the output to the log file String line = null; while ((line = br.readLine()) != null) { pw.println(line); } // add a small message with the return code to the log pw.println("********************************************"); pw.println("********************************************"); pw.println("Batch call completed with return status " + processStatus); pw.flush(); os.close(); } catch (IOException e) { logger.error("IOException raised during batch logging on file " + logFilePath, e); } catch (InterruptedException e) { logger.error("InterruptedException raised during batch process execution", e); } } } </code></pre> <p>My call is quite simple : </p> <pre><code>Process process = Runtime.getRuntime().exec(command); BatchThreadLogger logger = new BatchThreadLogger(process, logFilePath); logger.start(); </code></pre> <p>My command is currently just calling my test.bat with two parameters. My test batch now just do : </p> <pre><code>echo "BATCH CALLED WITH PARAMETER %1 AND %2" exit </code></pre> <p>My log file however does contains only : </p> <pre><code>******************************************** ******************************************** Batch call completed with return status 0 </code></pre> <p>I tried to place the <code>waitFor()</code>call before and after the code redirecting the output to the log file, without success. I always see the black screen of the command being launched, but nothing in logs...</p> <p>Any help would be greatly appreciated, I'm missing something, but cannot understand what...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload