Show stdout in file and in console (with System.setOut(new PrintStream(new File("output-file.txt"))

Viewed 919

I want to save the stdout into a file. For this, I used
System.setOut(new PrintStream(new File("output-file.txt")));

Now, there is no output in the console.

        try {
            System.setOut(new PrintStream(new File("output-file.txt")));
        } catch (Exception e) {
             e.printStackTrace();
        }

Is there any possibility to show the stdout in the console, although I use stdout to fill a file?

4 Answers

You could create a PrintWriter with an OutputStream that does both writes.

final OutputStream stdOut = System.out;
try {
    System.setOut(new PrintStream(new OutputStream() {
        private PrintStream ps = new PrintStream(new File("output-file.txt"));

        @Override
        public void write(int b) throws IOException {
            ps.write(b);
            stdOut.write(b);
        }

        @Override
        public void flush() throws IOException {
            super.flush();
            ps.flush();
            stdOut.flush();
        }

        @Override
        public void close() throws IOException {
            super.close();
            ps.close();
            // stdOut.close(); // Normally not done
        }
    }));
} catch (Exception e) {
    e.printStackTrace();
}

System.out.println("Hello, world!");

I never tried it, but i guess if you subclass the default Printstream you are able to print to console and file by yourself.

Something like:

class MyPrintStream extends printStream {

    private PrintStream secondPrinter;

    .....

    @Override 
    public void println(Object content) {
       super.println(content);
       secondPrinter.println(content);
    }
}

and maybe call it like this:

System.out = new MyPrintStream(myFile, System.out);

You can not use the systems OutputStream to write to 2 sources. It is a static variable and it can only have 1 value at a time.

You can try however, saving a reference to the consoles default OutputStream, and then changing the Systems OutputStream to your custom output stream, and write to both of them with a custom method.

Related