Can someone explain me the difference between OutputStream
and Writer
? Which of these classes should I work with?
Streams work at the byte level, they can read (InputStream) and write (OutputStream) bytes or list of bytes to a stream.
Reader/Writers add the concept of character on top of a stream. Since a character can only be translated to bytes by using an Encoding, readers and writers have an encoding component (that may be set automatically since Java has a default encoding property). The characters read (Reader) or written (Writer) are automatically converted to bytes by the encoding and sent to the stream.
OutputStream classes writes to the target byte by byte where as Writer classes writes to the target character by character
Character
in Java is a misnomer, as it actually represents an UTF-16 Code Unit, and not a Unicode Character or Code Point. –
Amin An OutputStream
is a stream that can write information. This is fairly general, so there are specialized OutputStream
for special purposes like writing to files. A stream can only write arrays of bytes.
Writer
s provide more flexibility in that they can write characters and even strings while taking a special encoding into account.
Which one to take is really a matter of what you want to write. If you do have bytes already, you can use the stream directly. If you have characters or strings, you either need to convert them to bytes yourself if you want to write them to a stream, or you need to use a Writer
which does that job for you.
OutputStream
, for example via an OutputStreamWriter
. –
Amin Writer
to write a string to a stream, which you can't do when using only a stream. Edited my answer to make this more clear. –
Alcheringa Writer
to write a string to a stream" –
Amin Writer
on the stream allows me to "write a string to a stream", even though technically the writer does the byte array conversion implicitly and writes a byte array to the stream. The result is the same, however. –
Alcheringa OutputStream
uses bare bytes, whereas Writer
uses encoded charaters.
Writer
uses UTF-16 Code Units, and not Encoded Characters –
Amin The Reader/Writer class hierarchy is character-oriented, and the Input Stream/Output Stream class hierarchy is byte-oriented. Basically there are two types of streams.Byte streams that are used to handle stream of bytes and character streams for handling streams of characters.In byte streams input/output streams are the abstract classes at the top of hierarchy,while writer/reader are abstract classes at the top of character streams hierarchy.
Cheers!!!
© 2022 - 2024 — McMap. All rights reserved.