2

Trying to change the encoding of System.out, I created a PrintWriter with

PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out, ENCODING));
so
out.format("some text");

worked fine as for the encoding. But

out.checkError()
didn't return true when the output stream was closed, e.g. by Unix 'head' command.

I've found that PrintStream offers a constructor with encoding

PrintStream out = new PrintStream(System.out, true, ENCODING);

and the checkError() worked fine for this class.

I doubt the PrintWriter case is a bug, or am I missing something?

1 Answers1

0

No, I also think that this is not a bug, but roots in a subtly different definition/design of checkError() and its underlying classes:

  • PrintWriter.checkError():

    public boolean checkError() Flushes the stream if it's not closed and checks its error state. Returns:true if the print stream has encountered an error, either on the underlying output stream or during a format conversion.

  • and from PrintStream.checkError():

    public boolean checkError() Flushes the stream and checks its error state. The internal error state is set to true when the underlying output stream throws an IOException other than InterruptedIOException, and when the setError method is invoked. If an operation on the underlying output stream throws an InterruptedIOException, then the PrintStream converts the exception back into an interrupt by doing: Thread.currentThread().interrupt(); or the equivalent. Returns: true if and only if this stream has encountered an IOException other than InterruptedIOException, or the setError method has been invoked.

As you see PrintStream's checkError()definition is the stricter one, and the fail maybe still worth an investigation.

And then much depends from your actual output console (and the encodings it supports.), e.g. in Windows, you need to:

chcp 65001

..to enable (e.g.) UTF-8 output.(https://stackoverflow.com/a/388500/592355, https://stackoverflow.com/a/10148976/592355, ...)

Community
  • 1
  • 1
xerx593
  • 12,237
  • 5
  • 33
  • 64