Search code examples
javasystem.outsystem.err

Reading System.Out


So, what I want to do is basically filter everything that is passed through System.out and System.err, is it possible to apply a filter of some sort or to create my own OutputStream to divert System.out with, and then process it normally?

Edit for clarity: To clarify, I need to read what goes out of System.out from other programs and manipulate it how I see fit, so a logger is not really an option as I do not have control over what the other program will use.

Edit for more clarity: I am creating a plugin for a larger program that needs to read everything written to System.out from other plugins. Because it is a plugin-based system the process my plugin is running on will always be the same one other plugins are running on.


Solution

  • Something I am not clear: you have mentioned that you want to "read what goes out of System.out from other programs". Are your application creating the process and want to monitor its standard out/err, or you want to monitor the standard out/err of your process itself?

    For former case, after you created the process, you can get its output, input and error stream.

    For latter case, you can replace the standard out of your Java process by System.setOut(yourOwnOutputStream);

    However, if you are trying to deal with streams of totally irrelevant process, I believe there is no way doing so without having the caller pipe the stdout/stderr to your process (unless through some platform specific methods)


    Update:

    In order to "intercept" the standard out, it is nothing different from all those classic "filter outputstreams". What you can do is something like this:

    import java.io.FilterOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    class AnalyzingOutputStream extends FilterOutputStream {
    
        public AnalyzingOutputStream (OutputStream out) {
            super(out);
        }
    
        @Override
        public void write(int b) throws IOException {
              // do whatever analysis you want
              super.write(b);  // delegate to super class' write, which will 
                               // delegate to the filtered outputstream
        }
        // other overrides
    }
    

    In order to use it, your main logic should do something like:

    AnalyzingOutputStream analyzingOutputStream = new AnalyzingOutputStream(System.out);
    System.setOut(analyzingOutputStream );
    
    // then you can call your methods of AnalyzingOutputStream to do whatever you want