How could I read Java Console Output into a String buffer(我如何将 Java 控制台输出读入字符串缓冲区)
问题描述
我有一个将一些文本输出到控制台的 Java 程序.它使用 print、println 和其他一些方法来执行此操作.
I have a Java program that outputs some text into console. It uses print, println, and some other methods to do this.
在程序结束时,我想读取控制台中的所有文本并将其复制到字符串缓冲区中.我怎么能在 Java 中做到这一点?我需要分别阅读stdout和stderr.
At the end of the program , I want to read all the text in console and copy it into a String buffer. How could I do this in Java ? I need to read stdout and stderr separately.
推荐答案
好的,这是一个有趣的问题.似乎不是一次解决所有 PrintStream 方法的优雅方法.(遗憾的是没有FilterPrintStream.)
Ok, this was a fun problem. Dosen't seem to be an elegant way of solving it for all PrintStream methods at once. (Unfortunately there is no FilterPrintStream.)
我确实写了一个丑陋的基于反射的解决方法(我想不要在生产代码中使用:)
I did write up an ugly reflection-based workaround though (not to be used in production code I suppose :)
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: -----
" + lpsOut.buf);
        System.out.println("----- Log for System.err: -----
" + lpsErr.buf);
    }
}
结果输出:
hello 5
Some error
----- Log for System.out: -----
hello 5
----- Log for System.err: -----
Some error
(请注意,FilterOutputStream 中的 out 字段受到保护和记录,因此它是 API 的一部分 :-)
(Note though, that the out field in FilterOutputStream is protected and documented, so it is part of the API :-)
这篇关于我如何将 Java 控制台输出读入字符串缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我如何将 Java 控制台输出读入字符串缓冲区
				
        
 
            
        基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
 - Java 实例变量在两个语句中声明和初始化 2022-01-01
 - 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
 - 从 python 访问 JVM 2022-01-01
 - Java Swing计时器未清除 2022-01-01
 - 大摇大摆的枚举 2022-01-01
 - 验证是否调用了所有 getter 方法 2022-01-01
 - 在 Java 中创建日期的正确方法是什么? 2022-01-01
 - 多个组件的复杂布局 2022-01-01
 - 不推荐使用 Api 注释的描述 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				