简体   繁体   中英

Redirecting Console Output Streams in Real-Time Using Java

I have a jar file that I do not have the source for (It's relatively old). I know that when it runs, it acts as a server (incoming and outgoing connections), and spits out a large amount of console output. What I want to do is have another java application kick it off using an exec, and redirect the stream within itself so that it can watch for certain keywords or timestamps within the output of the jar. The intent of the program is to keep track of certain events and provide a larger picture of when events happen, and "learn" how to react when they do happen in the future.

I'm guessing, from the reading I've done thus far, the tricky part is to get the data in real-time and not after the stream has been closed.

How would I go about doing this?

Extract your jar with a zip program. Look at the main class in the manifest

Create a new class

public class MyLogger {
    public static void main (String args[]) throws Exception {
         System.setOut(new PrintStream("out.txt"));
         System.setErr(new PrintStream("err.txt"));
         OriginalClassName.main(args);
    }
 }

Now simply build your class ( set the Javan class path to be your original .jar that you don't have the code for ) then once complete create a new .jar file with the jar tool and set your class to be the main one in the manifest

Now when you run you can use a tool like tail ( with the -f parameter ) to print the contents of file to a console while the file is being written in realtime. Tail is available on Linux and other Unix-platforms. For Windows install eg cygwin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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