DataOutStream Class in Java

In this article, we will learn how to use DataOutputStream class in Java with an example.

1. Introduction

DataOutputStream resides in the java.io package and serves as a filter for an underlying output stream to write data in a machine-independent format. It's commonly paired with DataInputStream to provide a symmetrical reading mechanism. 

2. Why Use DataOutputStream? 

Machine Independence: Data written by this stream can be read by DataInputStream without concerns about the machine where the data was originally written. 

UTF String Support: The writeUTF() method allows for efficient string encoding in a modified UTF-8 format. 

3. Constructing a DataOutputStream 

Typically, you create an instance by wrapping it around another output stream:

FileOutputStream fos = new FileOutputStream("dataFile.dat");
DataOutputStream dos = new DataOutputStream(fos);

4. Writing Data 

A few notable methods offered by DataOutputStream include: 

  • writeBoolean(boolean v): Writes a boolean. 
  • writeInt(int v): Outputs an integer. 
  • writeDouble(double v): Puts a double to the stream. 
  • writeUTF(String s): Encodes a string in UTF format. 

5. Diving Deep with an Example 

Let's create a basic program to illustrate the usage of DataOutputStream:

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputStreamDemo {

    public static void main(String[] args) {
        String filename = "dataOutputFile.dat";

        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename))) {
            
            dos.writeInt(2023);
            dos.writeDouble(10.23);
            dos.writeBoolean(false);
            dos.writeUTF("Java Rocks!");

            System.out.println("All data successfully written to " + filename);

        } catch (IOException e) {
            System.out.println("Oops! Something went wrong: " + e.getMessage());
        }
    }
}

// Expected Output:
// All data successfully written to dataOutputFile.dat

6. Things to Remember 

Binary Format: The resultant file from DataOutputStream contains binary data. You won't get much from viewing it in a regular text editor. 

Order is Essential: When retrieving data with DataInputStream, ensure to read data in the order it was written.

Related Java I/O Classes

Comments