【问题标题】:System.setOut() to a Preferences nodeSystem.setOut() 到 Preferences 节点
【发布时间】:2022-01-13 16:35:41
【问题描述】:

如何实现以下目标,其中 prefsOutputStream 是我要制作的伪变量:

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

【问题讨论】:

    标签: java io outputstream system.out


    【解决方案1】:

    我想到的一种方法是:

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

    这将创建一个PrintStream 输出到字节数组输出流。每当您打印换行符时,PrintStream 将自动刷新(例如,通过使用 println)。这将导致 ByteArrayOutputStream 刷新,这会将自上次刷新以来写入流的所有内容写入首选项。

    【讨论】:

    • 谢谢。效果很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多