Java DataOutputStream class

Introduction

DataOutputStream extends FilterOutputStream, which extends OutputStream.

It is used to write primitive type data to stream.

DataOutputStream defines the following constructor:

DataOutputStream(OutputStream outputStream) 

DataOutput has methods to convert a primitive type into a byte sequence.

Here is a sampling of these methods:

final void writeDouble(double value) throws IOException  
final void writeBoolean(boolean value) throws IOException  
final void writeInt(int value) throws IOException 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
   public static void main(String args[]) throws IOException {

      // First, write the data.
      try (DataOutputStream dout = new DataOutputStream(new FileOutputStream("Test.dat"))) {
         dout.writeDouble(98.6);/*from ww w . j  a v a 2 s .  com*/
         dout.writeInt(1000);
         dout.writeBoolean(true);

      } catch (FileNotFoundException e) {
         System.out.println("Cannot Open Output File");
         return;
      } catch (IOException e) {
         System.out.println("I/O Error: " + e);
      }

      // Now, read the data back.
      try (DataInputStream din = new DataInputStream(new FileInputStream("Test.dat"))) {

         double d = din.readDouble();
         int i = din.readInt();
         boolean b = din.readBoolean();

         System.out.println("Here are the values: " + d + " " + i + " " + b);
      } catch (FileNotFoundException e) {
         System.out.println("Cannot Open Input File");
         return;
      } catch (IOException e) {
         System.out.println("I/O Error: " + e);
      }
   }
}



PreviousNext

Related