我需要将 Getopt
类错误消息存储到字符串中。
通常该错误将打印在标准错误控制台中。
我该怎么做?
最佳答案
您也许可以使用System.setOut
和/或 System.setErr
.
举个例子:
static void printMessage()
{
System.out.println("Hello");
}
public static void main(String[] args) throws Exception
{
// ByteArrayOutputStream = in-memory output stream
OutputStream output = new ByteArrayOutputStream();
PrintStream oldStream = System.out; // store the current output stream
System.setOut(new PrintStream(output)); // change the output stream
printMessage(); // call function that prints to System.out
System.setOut(oldStream); // restore the old output stream
System.out.println("Output from stream: " + output.toString());
}
以上只会产生以下输出:
Output from stream: Hello
关于java - 如何将 Getopt 错误消息的输出重定向到字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19023069/