I'm designing a library where a class should have an ability to be able to convert itself internals into text. Which class shall I use: OutputStream
or Writer
? And what is the key difference between them (in my case)?
public interface Memento { void save(OutputStream stream); void save(Writer writer); }
Which one?
1.2 OutputStream: OutputStream is an abstract class of Byte Stream that describes stream output and it is used for writing data to a file, image, audio, etc. Thus, OutputStream writes data to the destination one at a time.
The major difference between these is that the input/output stream classes read/write byte stream data. Whereas the Reader/Writer classes handle characters. The methods of input/output stream classes accept byte array as parameter whereas the Reader/Writer classes accept character array as parameter.
The write method of OutputStream calls the write method of one argument on each of the bytes to be written out. Subclasses are encouraged to override this method and provide a more efficient implementation. If b is null , a NullPointerException is thrown.
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset . The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
An OutputStream
is a byte-oriented stream. Any text you write has to be encoded as bytes using some encoding (most commonly ISO-8859-1 or UTF-8). A Writer
is a character-oriented stream that may or may not internally encode characters as bytes, depending on what it is writing to.
EDIT If you are designing a library, then if you provide an OutputStream
-oriented interface to which text is to be written, you really should provide client classes the ability to control the encoding to be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With