栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将Java Console输出读入字符串缓冲区

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将Java Console输出读入字符串缓冲区

好的,这是一个有趣的问题。似乎不是一种同时解决所有

PrintStream
方法的优雅方法。(不幸的是没有
FilterPrintStream
。)

我确实写了一个丑陋的基于反射的解决方法(我想不要在生产代码中使用它:)

class LoggedPrintStream extends PrintStream {    final StringBuilder buf;    final PrintStream underlying;    LoggedPrintStream(StringBuilder sb, OutputStream os, PrintStream ul) {        super(os);        this.buf = sb;        this.underlying = ul;    }    public static LoggedPrintStream create(PrintStream toLog) {        try { final StringBuilder sb = new StringBuilder(); Field f = FilterOutputStream.class.getDeclaredField("out"); f.setAccessible(true); OutputStream psout = (OutputStream) f.get(toLog); return new LoggedPrintStream(sb, new FilterOutputStream(psout) {     public void write(int b) throws IOException {         super.write(b);         sb.append((char) b);     } }, toLog);        } catch (NoSuchFieldException shouldNotHappen) {        } catch (IllegalArgumentException shouldNotHappen) {        } catch (IllegalAccessException shouldNotHappen) {        }        return null;    }}

…可以像这样使用:

public class Test {    public static void main(String[] args) {        // Create logged PrintStreams        LoggedPrintStream lpsOut = LoggedPrintStream.create(System.out);        LoggedPrintStream lpsErr = LoggedPrintStream.create(System.err);        // Set them to stdout / stderr        System.setOut(lpsOut);        System.setErr(lpsErr);        // Print some stuff        System.out.print("hello ");        System.out.println(5);        System.out.flush();        System.err.println("Some error");        System.err.flush();        // Restore System.out / System.err        System.setOut(lpsOut.underlying);        System.setErr(lpsErr.underlying);        // Print the logged output        System.out.println("----- Log for System.out: -----n" + lpsOut.buf);        System.out.println("----- Log for System.err: -----n" + lpsErr.buf);    }}

结果输出:

hello 5Some error----- Log for System.out: -----hello 5----- Log for System.err: -----Some error

(不过请注意,其中的

out
字段
FilterOutputStream
已受到保护和记录,因此它是API的一部分:-)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/487014.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号