将stdout重定向到Java中的字符串 [英] Redirect stdout to a string in Java
本文介绍了将stdout重定向到Java中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道如何将stdout重定向到文件,但我不知道如何将其重定向到字符串。
I know how to redirect the stdout to a file, but I have no idea on how to redirect it to a string.
推荐答案
是 - 您可以使用 ByteArrayOutputStream
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
然后你可以用 baos.toString()获得字符串
。
要指定编码(而不依赖于平台定义的编码),请使用 PrintStream(stream,autoFlush,编码)
构造函数, baos.toString(编码)
To specify encoding (and not rely on the one defined by the platform), use the PrintStream(stream, autoFlush, encoding)
constructor, and baos.toString(encoding)
如果你想恢复到原始流,使用:
If you want to revert back to the original stream, use:
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
这篇关于将stdout重定向到Java中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文