DataOutputStream

In this chapter you will learn:

  1. How to use DataOutputStream
  2. How to use DataOutputStream to write primitive data to a file

Use DataOutputStream

DataOutputStream enables you to write primitive data to a stream. DataOutputStream implements the DataOutput interface.

DataOutput interface defines methods that convert primitive values to a sequence of bytes.

DataOutputStream makes it easy to store binary data, such as integers or floating-point values, in a file.

DataOutputStream extends FilterOutputStream, which extends OutputStream. DataOutputStream defines the following constructor:

DataOutputStream(OutputStream outputStream)

outputStream specifies the output stream to which data will be written.

DataOutput defines methods that convert values of a primitive type into a byte sequence and then writes it to the underlying stream.

Write primitive data to a file

DataOutputStream has methods for us to save value in primitive type into a file.

import java.io.DataOutputStream;
import java.io.FileOutputStream;
//from  ja v a  2  s .  co m
public class Main {

  public static void main(String args[]) throws Exception {

    FileOutputStream fos = new FileOutputStream("c:/a.txt");

    DataOutputStream dos = new DataOutputStream(fos);

    dos.writeShort(1);
    dos.writeBytes("java2s.com");
    dos.writeChar('a');
    dos.writeBoolean(true);

    fos.close();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use ObjectOutputStream
  2. How to save Java objects to a file with ObjectOutputStream