Java DataInputStream class

Introduction

Here is its only constructor:

DataInputStream(InputStream inputStream) 

We can use DataInputStream to read primitive types from stream.

final double readDouble() throws IOException  
final boolean readBoolean() throws IOException  
final int readInt() 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);//  w  w w. jav a2  s  .c o  m
         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