3

How do I send output from System.out to socket e.g. PrintWriter?

I need to send whatever appears on the console output (both std and err) to PrintWriter, thus a socket.

Thank you.

2 Answers2

4

May be you can try like this:

OutputStream os = socket.getOutputStream(); // for example
PrintStream ps = new PrintStream(os);
System.setOut(ps);
UVM
  • 9,776
  • 6
  • 41
  • 66
  • I would have to edit plenty of code to use PrintStream, at he moment I'm using PrintWriter. Any ideas on how to System.setOut() to PrintWriter? If it isn't doable then I'll have to switch to PrintStream. Thanks –  Jun 08 '12 at 10:07
  • 1
    you can do like this:PrintWriter out = new PrintWriter(System.out, true); – UVM Jun 08 '12 at 10:09
  • OK. But how Am I using it later?!? My PrintWriter already point to the socket: PrintWriter out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream())); and then I can do e.g. out.println(); Wouldn't your out print to console instead of socket?!? Correct me if I'm wrong I have to try this out. –  Jun 08 '12 at 10:14
  • Hence forth if you say System.out.println("hello"), will be redirected to socket – UVM Jun 08 '12 at 10:16
  • I don't seem to understand it ;( Where should I declare the out variable to use the socket? What order and how when I can't have duplicate declarations. –  Jun 08 '12 at 10:23
  • PrintWriter out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream())); and PrintWriter out = new PrintWriter(System.out, true); –  Jun 08 '12 at 10:23
  • 1
    PrintWriter out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream())); OutputStream os = new WriterOutputStream(out); PrintStream ps = new PrintStream(os); System.setOut(ps); – UVM Jun 08 '12 at 10:36
  • It worked fine after importing org.apache.commons.io... Thank you very much. After System.out.println(); There is a need for System.out.flush(); –  Jun 08 '12 at 11:15
0

Well, you can, but please be more specific about your requirements. If you want to send logging messages, you'll better use some logging framework like where you can switch from ConsoleAppender to SocketAppender immediately.

You can also replace System.out with System.setOut() and redirect output to some other target.

If you want to redirect the whole output of some application, you can try some bash/nc workaround as well:

$ java -jar your_app.jar | nc some_server
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Going for logging framework seems to be a good idea and should help me address other issues. Thank you. –  Jun 08 '12 at 10:09