Reputation: 105210
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?
Upvotes: 33
Views: 17857
Reputation: 5207
1) In many cases preferable can be overriding toString() or providing a similar method to convert ... internals into text. The advantage for user of such method is flexibility. For instance, if the consumer of such method can:
It can be disadvantage in some cases, e.g. when the text representation is relatively big (like 100 MB) and there are many requests simultaneously that produce such objects. This can require too much resources (CPU, RAM). In such case direct writing to a stream or to a writer can be preferable.
2) If you expect that you object can be used in many different contexts, then it makes sense to provide both, saving to a stream and saving to a writer. For instance, HttpServletResponse provides both, getWriter() and getOutputStream(), so that everyone can decide what is better in the his particular case. Or Jackson's JsonFactory provides methods * createGenerator()* for File, OutputStream and Writer, giving the consumer much freedom.
Upvotes: 0
Reputation: 234867
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.
Upvotes: 42
Reputation: 341003
Text? Writer
. It is intended for handling characters, honors encoding.
Stream/array of bytes? OutputStream
. Works on raw bytes, has no notion of characters, encodings, strings, etc.
Upvotes: 21