Ani
Ani

Reputation: 163

What is the difference between OutputStream and Writer?

Can someone explain me the difference between OutputStream and Writer? Which of these classes should I work with?

Upvotes: 14

Views: 19466

Answers (5)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56747

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.

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

Upvotes: 3

Vincent Robert
Vincent Robert

Reputation: 36150

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.

Upvotes: 19

Abhishek Ranjan
Abhishek Ranjan

Reputation: 931

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.

More details here

Cheers!!!

Upvotes: 1

DerMike
DerMike

Reputation: 16200

OutputStream uses bare bytes, whereas Writer uses encoded charaters.

Upvotes: 1

Chandra Sekhar
Chandra Sekhar

Reputation: 19500

OutputStream classes writes to the target byte by byte where as Writer classes writes to the target character by character

Upvotes: 8

Related Questions