开发者

How to write output of child process in Java

I have written a java code in Eclipse and i am developing a plug-in which embed a button on workbench. When this button is clicked, it opens a batch file (located in c:/program file/prism 4.0/bin)

The code successfully opens the .bat file ! But my next task is write the output of that batch file on my console. I am using Eclipse IDE version 3.

My code is

MessageConsoleStream out = myConsole.newMessageS开发者_JS百科tream();
        out.println("We are on console ! \n Shubham performed action");


try {

      ProcessBuilder pb=new ProcessBuilder("C:\\Program Files\\prism-4.0\\bin\\prism.bat");
        pb.directory(new File("C:\\Program Files\\prism-4.0\\bin"));
        Process p=pb.start();

        int exitVal=p.waitFor();            

       out.println("Exited with error code "+exitVal+" shown and action performed \n");

            out.println("Shubham Process Successful");
            out.println("Printing on console");

        }
        catch (Exception e)
        {
            out.println(e.toString());
            e.printStackTrace();

        }
    } 


Do like this:

.....
Process p = pb.start();

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

String in;
while((in = input.readLine()) != null) {
    out.println(in);
}

int exitVal = p.waitFor();
.....

Note that if the batch file writes to standard error your java program must consume it otherwise the p.waitFor() will never return.


Do yourself a big favor and check http://commons.apache.org/exec/. It will take care of all the awful details about managnig an external process: timeout, handling input/output, even creating the command line will be easier and less error prone


Note that to correctly read from the InputStreams of a Process, you should do so on separate Threads. See this similar question.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜