Search code examples
javafileasciioutputstream

Which OutputStream subclass to write to a text file


[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

Solution

    • The ByteArrayOutputStream is to write bytes to an in-memory byte[] variable.
    • The FileOutputStream is to write bytes to a File.
    • The FilterOutputStream is 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.
    • The ObjectOutputStream is 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.
    • The OutputStream is just the common abstract class of those streams. You can't construct it anyway. You can however declare against it.
    • The PipedOutputStream is intented to be able to write to another InputStream in a pipe so that the other side can read them from that InputStream.

    You want to write the data plain to a File, so the FileOutputStream is more than sufficient.

    try (OutputStream output = new FileOutputStream("/foo.txt")) {
        output.write(text.getBytes());
    }
    

    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 using String#getBytes(charset). E.g.:

        output.write(text.getBytes(StandardCharsets.UTF_8));
    

    Unrelated to the concrete question, the normal practice, however, is to use a Writer to write character data.

    If you don't care about character encoding, use FileWriter:

    try (Writer writer = new FileWriter("/foo.txt")) {
        writer.write(text);
    }
    

    It will use the platform default character encoding which will usually also support ASCII characters.

    If you care about character encoding, use OutputStreamWriter:

    try (Writer writer = new OutputStreamWriter(new FileOutputStream("/foo.txt"), StandardCharsets.UTF_8)) {
        // ...
    }
    

    It allows you for specifying the charset as 2nd argument while taking an OutputStream.

    See also: