【发布时间】:2010-10-08 14:34:59
【问题描述】:
我正在尝试使用 System.setOut 将 System.out 重定向到一个字符串,该字符串需要一个 PrintStream。有什么方法可以将 StringWriter 转换为 Stream 以便我可以将其传递给 setOut?
【问题讨论】:
我正在尝试使用 System.setOut 将 System.out 重定向到一个字符串,该字符串需要一个 PrintStream。有什么方法可以将 StringWriter 转换为 Stream 以便我可以将其传递给 setOut?
【问题讨论】:
您不能完全这样做,因为StringWriter 是Writer,而不是Stream。但你可以这样做:
// create a ByteArray stream, which will be wrapped by a PrintStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setOut(ps);
// print whatever you got
String result = baos.toString();
【讨论】: