Java - DataOutputStream Class



Introduction

The Java.io.DataOutputStream class lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

Class declaration

Following is the declaration for Java.io.DataOutputStream class −

public class DataOutputStream
   extends FilterOutputStream
      implements DataOutput

Field

Following are the fields for Java.io.DataOutputStream class −

  • protected int written − This is the number of bytes written to the data output stream so far.

  • protected OutputStream out − This is the underlying output stream to be filtered.

Class constructors

Sr.No. Constructor & Description
1

DataOutputStream(OutputStream out)

This creates a new data output stream to write data to the specified underlying output stream.

Class methods

Sr.No. Method & Description
1 void flush()

This method flushes this data output stream.

2 int size()

This method returns the current value of the counter written, the number of bytes written to this data output stream so far.

3 void write(byte[] b, int off, int len)

This method writes len bytes from the specified byte array starting at offset off to the underlying output stream.

4 void write(int b)

This method writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

5 void writeBoolean(boolean v)

This method writes a boolean to the underlying output stream as a 1-byte value.

6 void writeByte(int v)

This method writes out a byte to the underlying output stream as a 1-byte value.

7 void writeBytes(String s)

This method writes out the string to the underlying output stream as a sequence of bytes.

8 void writeChar(int v)

This method writes a char to the underlying output stream as a 2-byte value, high byte first.

9 void writeChars(String s)

This method writes a string to the underlying output stream as a sequence of characters.

10 void writeDouble(double v)

This method converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.

11 void writeFloat(float v)

This method converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.

12 void writeInt(int v)

This method writes an int to the underlying output stream as four bytes, high byte first.

13 void writeLong(long v)

This method writes a long to the underlying output stream as eight bytes, high byte first.

14 void writeShort(int v)

This method writes a short to the underlying output stream as two bytes, high byte first.

15 void writeUTF(String str)

This method writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

Methods inherited

This class inherits methods from the following classes −

  • Java.io.FilterOutputStream
  • Java.io.Object
  • Java.io.DataOutput

Example

Following is an example to demonstrate DataInputStream and DataOutputStream. This example write a string to a file test.txt using DataOutputStream.writeUTF() method and then reads the same using DataInputStream.readUTF() method.

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      InputStream is = null;
      DataInputStream dis = null;
      FileOutputStream fos = null;
      DataOutputStream dos = null;
      String[] buf = {"Hello", "World!!"};
      
      try {
         // create file output stream
         fos = new FileOutputStream("test.txt");
         
         // create data output stream
         dos = new DataOutputStream(fos);
         
         // for each string in the buffer
         for (String j:buf) {
         
            // write string encoded as modified UTF-8
            dos.writeUTF(j);        
         }
         
         // force data to the underlying stream
         dos.flush();
         
         // create file input stream
         is = new FileInputStream("test.txt");
         
         // create new data input stream
         dis = new DataInputStream(is);
         
         // read till end of the stream
         while(dis.available()>0) {
         
            // reads characters encoded with modified UTF-8
            String k = dis.readUTF();
            
            // print
            System.out.print(k+" ");
         }
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases all system resources from the streams
         if(is!=null)
            is.close();
         if(dos!=null)
            is.close();
         if(dis!=null)
            dis.close();
         if(fos!=null)
            fos.close();
      }
   }
}

Output

Hello World!! 

Example - Writing a Subarray of Bytes to a File

The following example shows the usage of Java DataOutputStream write(byte[] b, int off, int len) method.

DataOutputStreamDemo.java

package com.tutorialspoint;

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

public class DataOutputStreamDemo {
   public static void main(String[] args) {
      try {
         // Create a DataOutputStream to write to a file
         FileOutputStream fileOutput = new FileOutputStream("output.dat");
         DataOutputStream dataOutput = new DataOutputStream(fileOutput);

         // Byte array containing ASCII values of 'Hello, World!'
         byte[] message = "Hello, World!".getBytes();

         // Write only "World!" (start at index 7, length 6)
         dataOutput.write(message, 7, 6);

         // Close stream
         dataOutput.close();
         System.out.println("Data successfully written to output.dat");

      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Data successfully written to output.dat

Explanation

  • Create a file output stream (FileOutputStream) and wrap it with DataOutputStream.

  • Convert a string ("Hello, World!") to a byte array using .getBytes().

  • Write only "World!" from the byte array:

    • Offset (7) − Starts from 'W'

    • Length (6) − Writes 'World!'

  • File (output.dat) will contain: World!

  • Close the stream to save data properly.

Example - Writing and Reading a Boolean to/from a File

The following example shows the usage of Java DataOutputStream writeBoolean(boolean v) method.

DataOutputStreamDemo.java

package com.tutorialspoint;

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

public class DataOutputStreamDemo {
   public static void main(String[] args) {
      try {
         // Create a DataOutputStream to write to a file
         FileOutputStream fileOutput = new FileOutputStream("output.dat");
         DataOutputStream dataOutput = new DataOutputStream(fileOutput);

         // Write boolean values
         dataOutput.writeBoolean(true);
         dataOutput.writeBoolean(false);
         dataOutput.writeBoolean(true);

         // Close the output stream
         dataOutput.close();
         System.out.println("Boolean values successfully written to output.dat");

         // Read the boolean values back
         FileInputStream fileInput = new FileInputStream("output.dat");
         DataInputStream dataInput = new DataInputStream(fileInput);

         // Read and print the boolean values
         System.out.println("First boolean: " + dataInput.readBoolean());  // true
         System.out.println("Second boolean: " + dataInput.readBoolean()); // false
         System.out.println("Third boolean: " + dataInput.readBoolean());  // true

         // Close the input stream
         dataInput.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Boolean values successfully written to output.dat
First boolean: true
Second boolean: false
Third boolean: true

Explanation

Writing Boolean Values

  • FileOutputStream creates a file (booleanData.dat).

  • DataOutputStream.writeBoolean(true) writes 1 (one byte).

  • DataOutputStream.writeBoolean(false) writes 0 (one byte).

  • DataOutputStream.writeBoolean(true) writes 1 (one byte).

  • The file now contains { 1, 0, 1 }.

Reading Boolean Values

  • FileInputStream opens the file.

  • DataInputStream.readBoolean() reads each byte and converts it to true (1) or false (0).

Advertisements