Java.Streams.What classes allow you to convert byte streams to character streams and back?

🔁 Classes that Convert Between Byte and Character Streams

🔹 1. InputStreamReader

  • Converts: InputStreamReader
  • Direction: Byte → Character
  • Use case: Reading a byte stream (e.g., from a file or network) as text.

✅ Example:

InputStream is = new FileInputStream("input.txt");
Reader reader = new InputStreamReader(is, "UTF-8");
  • Wraps an InputStream
  • Decodes bytes into characters using a charset (e.g., UTF-8)

🔹 2. OutputStreamWriter

  • Converts: WriterOutputStream
  • Direction: Character → Byte
  • Use case: Writing text to an OutputStream, like saving to a file or sending over a network.

✅ Example:

OutputStream os = new FileOutputStream("output.txt");
Writer writer = new OutputStreamWriter(os, "UTF-8");
  • Encodes characters into bytes using a charset

🌐 Why is this important?

Because:

  • Streams are binary, but most data we handle is text.
  • You need to decode incoming bytes to characters when reading text.
  • You need to encode characters to bytes when writing text.

🧵 TL;DR

ClassConvertsDirectionCharset-aware?Use Case
InputStreamReaderInputStream → ReaderByte → Char✅ YesRead bytes as text
OutputStreamWriterWriter → OutputStreamChar → Byte✅ YesWrite text as bytes
This entry was posted in Без рубрики. Bookmark the permalink.