How to work with binary files OutputStream

A subset of the OutputStream hierarchy

  • OutputStream <<abstract>>
    • FileOutputStream
    • FilterOutputStream
      • BufferedOutputStream
      • DataOutputStream <<implements DataOutput interfaces>>

Classes used to connect a binary output stream to a file

  • DataOutputStream – writes data to the stream
    • BufferedOutputStream – creates a buffer for the stream
      • FileOutputStream – connects the stream to a file

Constructors of these classes:

Constructors Throws
DataOutputStream(OutputStream) none
BufferedOutputStream(OutputStream) none
FilterOutputStream(File [,booleanAppend]) IOException
FilterOutputStream(StringFileName [ , booleanAppend]) IOException

Example 1: A File object that refers to a binary file

File productsFile = new File("products.dat")

Example 2: How to connect to a file with a buffer

DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FilterOutputStream(productsFile)));

Example 3: How to connect for an append operation

DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FilterOutputStream(productsFile, true)));

Descriptions:

  • All classes in java.io and java.util.zip packages that end with OutputStream are members of the OutputStream hierarchy.

Warning:

  • By default, the output file is overwritten.

More info can be found here: http://www.j2ee.me/javase/6/docs/api/java/io/OutputStream.html