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

Makuna :

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?

TiiJ7 :

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!");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=133748&siteId=1