How to convert a Reader to InputStream and a Writer to OutputStream?

前端 未结 12 2163
慢半拍i
慢半拍i 2020-12-02 07:31

Is there an easy way to avoid dealing with text encoding problems?

12条回答
  •  不知归路
    2020-12-02 08:09

    Use:

    new CharSequenceInputStream(html, StandardCharsets.UTF_8);
    

    This way does not require an upfront conversion to String and then to byte[], which allocates lot more heap memory, in case the report is large. It converts to bytes on the fly as the stream is read, right from the StringBuffer.

    It uses CharSequenceInputStream from Apache Commons IO project.

提交回复
热议问题