gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:10:09 26 4
gpt4 key购买 nike

尝试更改 System.out 的编码,我创建了一个 PrintWriter

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

out.format("some text");

编码工作正常。但是

out.checkError()
没有返回 true当输出流关闭时,例如通过 Unix 'head' 命令。

我发现 PrintStream 提供了一个带编码的构造函数

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

和 checkError()这门课效果很好。

我怀疑 PrintWriter 的情况是错误,还是我遗漏了什么?

最佳答案

不,我也认为这不是错误,而是根源于 checkError() 及其基础类的定义/设计略有不同:

  • 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.

  • 来自 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.

如您所见,PrintStreamcheckError() 定义更为严格,失败可能仍值得研究。

然后很大程度上取决于您的实际输出控制台(及其支持的编码),例如在 Windows 中,您需要:

chcp 65001

..启用(例如)UTF-8 输出。( https://stackoverflow.com/a/388500/592355 , https://stackoverflow.com/a/10148976/592355 , ...)

关于Java: checkError() for PrintWriter(OutputStreamWriter(System.out)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12929958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com