简体   繁体   中英

Java: checkError() for PrintWriter(OutputStreamWriter(System.out))

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

PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out, ENCODING));
so

out.checkError()

worked fine as for the encoding. But

 out.checkError()  
didn't return true when the output stream was closed, eg 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?

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.), eg in Windows, you need to:

chcp 65001

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM