DataInputStream

DataInputStream enable you to read primitive data from a stream.

It implements DataInput interface.

DataInput interface defines methods that convert primitive values from a sequence of bytes.

DataInputStream makes it easy to store binary data, such as integers or floating-point values, in a file. DataInputStream extends FilterInputStream, which extends InputStream, and it implements the DataInput interface.

Here is its only constructor:


DataInputStream(InputStream inputStream)

inputStream specifies the input stream from which data will be read.

DataInputStream reads a sequence of bytes and convert them into values of a primitive type.

Here is a sampling of these methods:


double readDouble( ) throws IOException 
boolean readBoolean( ) throws IOException 
int readInt( ) throws IOException

The following program demonstrates the use of DataOutputStream and DataInputStream:


import java.io.DataInputStream;
import java.io.FileInputStream;

public class MainClass {

  public static void main(String args[]) {
    try {

      FileInputStream fis = new FileInputStream("fileName.dat");

      // Create a data input stream
      DataInputStream dis = new DataInputStream(fis);

      // Read and display data
      System.out.println(dis.readBoolean());
      System.out.println(dis.readByte());
      System.out.println(dis.readChar());
      System.out.println(dis.readDouble());
      System.out.println(dis.readFloat());
      System.out.println(dis.readInt());
      System.out.println(dis.readLong());
      System.out.println(dis.readShort());

      // Close file input stream
      fis.close();
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}
Home 
  Java Book 
    File Stream  

DataInputStream:
  1. DataInputStream
  2. new DataInputStream(FileInputStream fileInputStream)
  3. new DataInputStream(new BufferedInputStream(new FileInputStream("temp.tmp")))
  4. DataInputStream: readUnsignedShort()
  5. DataInputStream: readUTF()