javaiooutputstreamsystem.out

System.setOut() to a Preferences node


How can I achieve the following, where prefsOutputStream is the pseudo-variable I'm aiming to make:

PrintStream oldOut = System.out;

System.setOut(prefsOutputStream);

System.out.println("Foo Bar");

String logString = Preferences.userRoot().node("app").get("stdout","");
oldOut.println(logString); // Outputs "Foo Bar" into the console

Solution

  • One way I thought of is:

    System.setOut(new PrintStream(new ByteArrayOutputStream() {
        @Override
        public void flush() throws IOException {
            super.flush();
            String old = Preferences.userRoot().node("app").get("stdout", "");
            Preferences.userRoot().node("app").put("stdout", old + toString(StandardCharsets.UTF_8));
            count = 0;
        }
    }, true, StandardCharsets.UTF_8));
    

    This creates a PrintStream that outputs to a byte array output stream. The PrintStream will be automatically flushed whenever you print a newline character (e.g. by using println). This will cause the ByteArrayOutputStream to flush, which will write everything written to the stream since the last flush, to the preferences.