Process output from apache-commons exec

后端 未结 4 1579
予麋鹿
予麋鹿 2020-12-10 10:11

I am at my wits end here. I\'m sure this is something simple and I most likely have huge holes in my understanding of java and streams. I think there are so many classes tha

4条回答
  •  再見小時候
    2020-12-10 10:59

    Its a very old thread but I had to use Apache Commons Exec and had to solve the same problem. I trust with last version of Apache Commons Exec published in 2014, below solution works well both with and without watchdog;

    class CollectingLogOutputStream implements ExecuteStreamHandler {
    private final List lines = new LinkedList();
    public void setProcessInputStream(OutputStream outputStream) throws IOException 
    {
    }
    //important - read all output line by line to track errors
    public void setProcessErrorStream(InputStream inputStream) throws IOException {
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader br = new BufferedReader(isr);
        String line="";
        while( (line = br.readLine()) != null){
            //use lines whereever you want - for now just print on console
            System.out.println("error:"+line);
        }
    }
    //important - read all output line by line to track process output
    public void setProcessOutputStream(InputStream inputStream) throws IOException 
    {
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader br = new BufferedReader(isr);
        String line="";
        while( (line = br.readLine()) != null){
            //use lines whereever you want - for now just print on console
            System.out.println("output:"+line);
        }
      }
    
    public void start() throws IOException {
    }
    
    public void stop() throws IOException {
    }
    }
    

    Above class can be set as StreamHandler for the executor as below;

    //set newly created class stream handler for the executor
    executor.setStreamHandler(new CollectingLogOutputStream());
    

    Complete code is available here; https://github.com/raohammad/externalprocessfromjava

提交回复
热议问题