[Assignment]
Requirement
Use specifically OutputStream subclasses to output data to a .txt file, that can be read by a person using a program like Notepad.
(so a Writer is not an option)
Thoughts
May be ASCII or any human-readable character set.
Question
Which one of these do I use?
- ByteArrayOutputStream
- FileOutputStream
- FilterOutputStream
- ObjectOutputStream
- OutputStream
- PipedOutputStream
ByteArrayOutputStreamis to write bytes to an in-memorybyte[]variable.FileOutputStreamis to write bytes to aFile.FilterOutputStreamis a common superclass for more specific output streams which manipulate the data beforehand, such as encryption/decryption, calculating checksum, character encoding, compressing (zipping), etcetera. It does by itself nothing special.ObjectOutputStreamis to write fullworthy Java types and objects in a serialized form into a byte stream. It basically allows to convert complex Java objects to raw bytes and vice versa.OutputStreamis just the common abstract class of those streams. You can’t construct it anyway. You can however declare against it.PipedOutputStreamis intented to be able to write to anotherInputStreamin a pipe so that the other side can read them from thatInputStream.You want to write the data plain to a
File, so theFileOutputStreamis more than sufficient.Note that
String#getBytes()uses the platform default encoding to convert characters to bytes. If you’re using "special characters" which are not covered by at least ASCII, then you should always explicitly specify the charset usingString#getBytes(charset). E.g.:Unrelated to the concrete question, the normal practice, however, is to use a
Writerto write character data.If you don’t care about character encoding, use
FileWriter:It will use the platform default character encoding which will usually also support ASCII characters.
If you care about character encoding, use
OutputStreamWriter:It allows you for specifying the charset as 2nd argument while taking an
OutputStream.See also: