开发者

Run a batch file from Java program and get the status of execution

I need to run a Batch file from my Java Program and know if that was completed or not.

try{
    Process process = Runtime.getRuntime().exec( command );

    if( null!=process  && process.waitFor() == 0 &&process.exitValue()== 0 )
     {
        LOGGER.debug("Command executed successfuly.["+command+"]");
        return 0;
    }
    else{
        LOGGER.debug( "Error while getting the modified log" );
        return 1;
    }
}
catch( IOException e ){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch( InterruptedException e ){
// TODO Auto-generated catch block
e.printStackTrace();
}

My command is something similar to this cmd /c C:/Test/test.bat This test.bat file takes some 10-15 minutes to complete. Immediately after this is executed, process.exitValue() returns 0. But I need to know if this was executed completely or not. In my test.bat file, I'm calling another exe file which performs some operations. That exe file writes some error information to the console.I need to get that information.

Is it possible to know this from Java code? Or Can someone please let me know the best way to check this? I thought of some approaches like writi开发者_如何学运维ng the status(after successful completion) to a text file (from the batch program) and then check this from Java code. But I don't think that is the correct way to do this.


Here's what I'm doing:

Process process = Runtime.getRuntime().exec(execString);
if (log.isDebugEnabled()) {
   log.debug("Result: " + IOUtils.toString(process.getInputStream()));
   log.debug("Error: " + IOUtils.toString(process.getErrorStream()));
}
if (process.waitFor() == 0) { .. }


I don't know what your file test.bat does, but I wouldn't try to parse the output stream if I could change that bat file. Change test.bat so that it actually uses exit codes, and define exit codes so that they indicate what type of error you have.

The value returned by waitFor will then indicate if the execution terminated successfully, or how it failed if it failed.

Btw. You should always read stdout and stderr from processes since execution can halt if the buffers for those streams get full.


Use Process.getOutputStream(). See here.


I got an answer from this site. http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜