Mostrar la salida estándar de archivo y en la consola (con System.setOut (nueva PrintStream (nuevo archivo ( "output-archivo.txt"))

fotos:

Quiero salvar a la salida estándar en un archivo. Para ello, he utilizado
System.setOut(new PrintStream(new File("output-file.txt")));

Ahora, no hay salida en la consola.

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

¿Hay alguna posibilidad de mostrar la salida estándar de la consola, aunque yo uso la salida estándar para llenar un archivo?

TiiJ7:

Se puede crear una PrintWritercon una OutputStreamque hace las dos escrituras.

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

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=237282&siteId=1
Recomendado
Clasificación