Java新手问题:
我需要捕获第三方组件写入printStream的文本.
PrintStream默认为System.err,但可以更改为另一个PrintStream.
浏览文档,我找不到一种简单的方法将PrintStream的内容定向到字符串编写器/缓冲区.
有人可以帮忙吗?
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
System.setOut(new PrintStream(pipeOut));
// now read from pipeIn
Run Code Online (Sandbox Code Playgroud)
import java.io.*;
public class Test {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("errors.txt");
} catch(IOException ioe) {
System.err.println("redirection not possible: "+ioe);
System.exit(-1);
}
PrintStream ps = new PrintStream(fos);
System.setErr(ps);
System.err.println("goes into file");
}
}
Run Code Online (Sandbox Code Playgroud)
您可以围绕任何其他OutputStream创建PrintStream.
创建一个转到内存缓冲区的最简单方法是:
PrintStream p = new PrintStream( new ByteArrayOutputStream() )
Run Code Online (Sandbox Code Playgroud)
然后,您可以在任何您喜欢的点读取和重置字节数组的内容.
另一种可能性是使用管道.
InputStream third_party_output = new PipedInputStream();
PrintStream p = new PrintStream( new PipedOutputStream( third_party_output ) );
Run Code Online (Sandbox Code Playgroud)
然后,您可以从third_party_output流中读取以获取库写入的文本.
| 归档时间: |
|
| 查看次数: |
9311 次 |
| 最近记录: |