从另一个获取正在运行的Java程序的输出

从另一个获取正在运行的Java程序的输出

本文介绍了从另一个获取正在运行的Java程序的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java程序,可以编译并运行其他Java程序.我也有.txt文件,这些文件的输入被输入到其他Java程序中.

I have a Java program that compiles and runs other Java programs. I also have .txt files that have inputs that are fed into the other Java programs.

我想知道如何做的是捕获运行这些输入文件的输出?

What I want to know how to do is to capture the output of running with those input files?

推荐答案

我假设您正在通过ProcessBuilder或Runtime.exec()调用另一个程序,都返回一个具有getInputStream()和getErrorStream方法的Process对象.(),让您可以监听其他进程的输出和错误(stdout,stderr)流.

I'm assuming you're invoking the other program through either ProcessBuilder or Runtime.exec() both return a Process object which has methods getInputStream() and getErrorStream() which allow you to listen on the output and error (stdout, stderr) streams of the other process.

考虑以下代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {

    public static void main(String[] args){
        Test t = new Test();

        t.start();
    }

    private void start(){
        String command = //Command to invoke the program

        ProcessBuilder pb = new ProcessBuilder(command);

        try{
            Process p = pb.start();

            InputStream stdout = p.getInputStream();
            InputStream stderr = p.getErrorStream();

            StreamListener stdoutReader = new StreamListener(stdout);
            StreamListener stderrReader = new StreamListener(stderr);

            Thread t_stdoutReader = new Thread(stdoutReader);
            Thread t_stderrReader = new Thread(stderrReader);

            t_stdoutReader.start();
            t_stderrReader.start();
        }catch(IOException n){
            System.err.println("I/O Exception: " + n.getLocalizedMessage());
        }
    }

    private class StreamListener implements Runnable{
        private BufferedReader Reader;
        private boolean Run;

        public StreamListener(InputStream s){
            Reader = new BufferedReader(new InputStreamReader(s));
            Run = true;
        }

        public void run(){
            String line;

            try{
                while(Run && (line = Reader.readLine()) != null){
                    //At this point, a line of the output from the external process has been grabbed. Process it however you want.
                    System.out.println("External Process: " + line);
                }
            }catch(IOException n){
                System.err.println("StreamListener I/O Exception!");
            }
        }
    }
}

这篇关于从另一个获取正在运行的Java程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:37