Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writer or OutputStream?

Tags:

java

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?

like image 916
yegor256 Avatar asked Mar 07 '11 18:03

yegor256


People also ask

What is an OutputStream?

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.

What is the difference between reader/writer and Inputstream OutputStream?

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.

What is OutputStream write?

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.

What is OutputStream Writer in java?

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.


1 Answers

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.

like image 66
Ted Hopp Avatar answered Sep 30 '22 08:09

Ted Hopp