开发者

Need guidance to automate a multiple .bat file processes

I want to create a utility in Java to automate our building process. The current process involve

  • Opening 2 consoles for servers. ( I want to open these consoles from开发者_Go百科 java program )
  • Running mulitple bat files in consoles and based on one batch file output, running other commands.

I need head start, what libraries should i use. Can i open 2 consoles from Java (independently). Like even if my program closes those consoles keep running. (consoles are bea server, startWebLogic.cmd).


Alee, yes you can do that with Runtime.getRuntime().exec("file.bat"); and then you have 2 options, you can capture the output of the execution

for example:

public static void main(String[] args) {
    System.out.println("hello");
    try {
        Process p = Runtime.getRuntime().exec("./prog.sh");
        InputStream in = p.getInputStream();

        System.out.println("OUTPUT");
        StringBuilder sb = new StringBuilder();
        int c;
        while( (c = in.read() ) > 0 ) {
            sb.append((char) c);
        }

        //here the script finished
        String output = sb.toString();
        if( output.contains("Exception")) { 
            System.out.println("script failed");
        }

        if( p.exitValue() == 0) {
            System.out.println("The script run without errors");
        } else {
            System.out.println("The script failed");
        }
    } catch (IOException e) {
        e.printStackTrace(); 
    }
}

this captures both scenarios, where you need to capture the output and then decide whether the script run successfully, or if you can use the exit status from the script.

The exitValue code is 0 for success and any other number for failure.


Surely you can open as many consoles as you want. If you wish to do it simultaneously creaete separate threads and then create process using Runtime.exec() or ProcessBuilder.

But why do you want to do this? There is a good old ant that is a build tool dedicated for such tasks. It supports everything and it is extendable using custom tasks.

Moreover if you suddenly remember that it is 2011 now, use newer tools like Apache Buildr.


Java's Runtime class has methods to launch Processes which have programmatic interfaces to their input/output streams and other management. However, I'm not sure how Windows handles processes whose parents have died.

You should also consider using the Windows Script Host via VB or JScript as you will probably have finer control.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜