简体   繁体   English

Java中子进程的output怎么写

[英]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.我在 Eclipse 中编写了 java 代码,我正在开发一个在工作台上嵌入按钮的插件。 When this button is clicked, it opens a batch file (located in c:/program file/prism 4.0/bin )单击此按钮时,它将打开一个批处理文件(位于c:/program file/prism 4.0/bin

The code successfully opens the.bat file.代码成功打开.bat文件。 But my next task is write the output of that batch file on my console.但我的下一个任务是在我的控制台上编写该批处理文件的 output。 I am using Eclipse IDE version 3.我正在使用 Eclipse IDE 版本 3。

My code is我的代码是

MessageConsoleStream out = myConsole.newMessageStream();
        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.请注意,如果批处理文件写入标准错误,您的 java 程序必须使用它,否则p.waitFor()将永远不会返回。

Do yourself a big favor and check http://commons.apache.org/exec/ .帮自己一个大忙,检查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.请注意,要正确读取进程的 InputStreams,您应该在单独的线程上执行此操作。 See this similar question .看到这个类似的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM