SoFunction
Updated on 2025-03-02

How to convert character streams and byte streams in IO streams in Java

Conversion of character streams and byte streams

Java only provides a method to convert byte streams into character streams, and there is no method to convert characters into byte streams.

Because the byte stream is a general stream, it can transmit various types of resources, such as: text, pictures, audio, etc.

A character stream is a special stream that can only transmit text-type resources, but it is more convenient and faster than a byte stream to transmit text.

Therefore, some scenarios need to convert byte streams into more convenient and fast character streams to process; but no scenarios need to convert characters into byte streams, which is easy to understand. If it is a text type, the character stream is more efficient and does not need to convert to byte streams. If it is another type, the character stream cannot be used at all, and there is no conversion.

Convert a byte stream into a character stream, which can be used

Convert exclusive streams

The constructor of this class is 4 overloaded methods

The parameter can be a character stream object

Or character stream object + character set name/charset object/charset decoder object

public InputStreamReader(InputStream in) {}

public InputStreamReader(InputStream in, String charsetName)
throws UnsupportedEncodingException {}

public InputStreamReader(InputStream in, Charset cs) {}

public InputStreamReader(InputStream in, CharsetDecoder dec) {}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.