1

I need to store Getopt class error message to a string.

Normally that error will be printed in standard error console.

How would I do this?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
user2572969
  • 267
  • 1
  • 4
  • 17
  • I dont understand your question. – Mohayemin Sep 26 '13 at 08:29
  • 1
    Do you mean an **exception**? [This might help](http://stackoverflow.com/questions/1149703/stacktrace-to-string-in-java). However, we wouldn't have to guess if you showed us your code, and your exact requirements, and what the code does instead... – ppeterka Sep 26 '13 at 08:34

1 Answers1

1

You may be able to use System.setOut and/or System.setErr.

As an example:

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());
}

The above will lead to only the following output:

Output from stream: Hello
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138