Java 如何将Getopt错误消息的输出重定向到字符串?

Java 如何将Getopt错误消息的输出重定向到字符串?,java,Java,我需要将Getopt类错误消息存储到字符串中 通常,该错误将在标准错误控制台中打印 我该怎么做?您可以使用和/或 例如: static void printMessage() { System.out.println("Hello"); } public static void main(String[] args) throws Exception { // ByteArrayOutputStream = in-memory output stream OutputStream

我需要将
Getopt
类错误消息存储到字符串中

通常,该错误将在标准错误控制台中打印

我该怎么做?

您可以使用和/或

例如:

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
您可以使用和/或

例如:

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

我不明白你的问题。你是说例外吗。然而,我们不必猜测你是否向我们展示了你的代码,你的确切要求,以及代码的作用……我不理解你的问题。你是说例外吗。但是,我们不必猜测您是否向我们展示了您的代码,以及您的确切需求,以及代码的功能。。。