Automatic conversion of System.out output Tag(s): IO


  • Convert System.out output to uppercase.
    import java.io.PrintStream;
    
    public class Test {
      public static void main(String[] args) throws Exception {
    
        System.setOut(new PrintStream(System.out) {
           public void println(String s) {
             super.println(s.toUpperCase());
           }
        });
    
        System.out.println("hello world"); // output :  HELLO WORLD
     }
    }
    
  • Replace the regular output stream of System.out to do useful thing like implementing a Tee mechanism to output to the console and to file.
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.PrintStream;
    
      public class TeeOutputStream extends OutputStream {
        private OutputStream os1;
        private OutputStream os2;
    
        public TeeOutputStream(OutputStream os1, OutputStream os2) {
          this.os1 = os1;
          this.os2 = os2;
        }
    
        public void write(int i) throws IOException {
          os1.write(i);
          os2.write(i);
        }
    
        public void flush() throws IOException {
          os1.flush();
          os2.flush();
        }
        public void close() throws IOException {
          os1.close();
          os2.close();
        }
    
        public static void main(String[] args) throws IOException {
          System.out.println("Starting...");
          // keep the original
          PrintStream originalOutStream = System.out;
          System.setOut(
               new PrintStream(
                   new TeeOutputStream(
                       System.out,
                       new PrintStream("C:/temp/howto.out"))));
          // restore the original
    
          System.out.println("*");
          for (int i = 1; i<= 10; i++) {
            System.out.println(i);
          }
          System.out.println("*");
    
          System.setOut(originalOutStream);
          System.out.println("Done. Check the log");
        }
      }
    

    blog comments powered by Disqus