DataInputStream class

 

 

  DataInputStream extends FilterInputStream and implements the DataInput interface.

 

  For its methods:  See  DataInput interface  and  InputStream class  

 

It has these methods because it implements DataInput:

 

 

Plus it has these methods because it extends InputStream:

.readBoolean( )                     Reads one byte and returns true or false if it was

                                                zero or non-zero.

.readByte( )                            Reads and returns a byte.

.readChar( )                           Reads and returns a char.

.readDouble( )                       Reads eight bytes and returns a double.

.readFloat( )                           Reads four bytes and returns a float.

.readFully( byte[ ] )               Reads bytes into an array.

.readFully( byte[ ], offset, len)     Reads len bytes into an arry starting at offset.

.readInt( )                               Reads four bytes and returns an int.

.readLine( )                            Reads the next line of text from the input stream.

.readLong( )                          Reads eight bytes and returns a long.

.readShort( )                          Reads two bytes and returns a short.

.readUnsignedByte( )           Reads a byte, extends it to int, returns it in the range 0 -255.

.readUnsignedShort( )         Reads two bytes and returns an int in range 0 to 65535.

.readUTF( )                             Reads in a String encoded using a modified UTF-8 format. 

.skipBytes( num )                 Skips num bytes of the input stream.

available( )             Tells how many bytes can be gotten without blocking.

close( )                   Close the stream.

mark( int readAheadLimit )  Mark the present position in the stream.

markSupported( )                 Tell whether this stream supports mark(...).

read( )                     Read a single byte, returning it as the low end of an int.

read( byte[ ] b )     Read bytes into a byte array.

read( byte[ ] b, int off, int len)  Read bytes into a portion of a byte array.

ready( )                   Tell whether this stream is ready to be read.

reset( )                    Reset the stream to the beginning.

skip( long n )         Skip characters.

 

  DataInputStream reads streams of the binary format of data primitive types which were written by DataOutputStream.

 

  The data is machine-independent, so DataInputStream/ DataOutputStream is the preferred way of dealing with cross-machine needs.

 

   Its readByte( ) method will read any old byte file:

 

                    import java.io.*;
 
try {
DataInputStream dis = new DataInputStream( new BufferedInputStream( new FileInputStream( "test.txt")));
while(dis.available( ) != 0)
System.out.print( (char) dis.readByte( ) );
} catch ( IOException e) {    }

 

 

  The snippet below provides a method called readVarRcds which accepts a File object as its only parameter. The method presumes that the file is an ASCII or UTF-8 file containing variable-length records.  Each record consists of a two-byte binary length field followed by a series of text characters.  The method uses readFully(...) to read the file.  It uses the variable length fields for the records but does not return them.  It returns a Vector of elements containing the records from the file. If an exception occurs it returns a null Vector.

 

For a method which writes this type of file, see the writeBytes(...)  method examples under DataOutput interface.

 

import java.io.*;
 
public Vector readVarRcds( File f ) {
Vector v = new Vector( );
try {
    DataInputStream dis = new DataInputStream( new FileInputStream( f ));
    while (true) {
        short sh = dis.readShort( );
        byte[ ] b = new byte[ sh ];
        dis.readFully( b );
        String s = new String( b );
        v.addElement( s );
        }
}
catch (EOFException e) { return v; }
catch (Exception ex) { v = null; return v; }
}

 

 

  The following code reads some ints from a file written there by DataOutputStream.

 

import java.io.*;

 

File f = new File("c://temp.txt");

DataInputStream dis = null;

DataOutputStream dos = null;

 

try  { dos = new DataOutputStream(new FileOutputStream(f));

        for (int i=0; i<10; i++) dos.writeInt(i);  }

catch (IOException ex)  {  }

finally  { try  { if (dos != null) dos.close( ); }

                     catch (IOException ex)  {  }       }

 

try  { dis = new DataInputStream(new FileInputStream(f));

                for (int i=0; i<10; i++)  System.out.print("  " + dis.readInt( ));   }

catch (FileNotFoundException ex)  {  }

catch (IOException ex)  {  }

finally  { try  { if (dis != null) dis.close( );   }

                     catch (IOException ex)  {  }   }

 

 

  Read fixed length record files.  The following snippet provides a sample method named readByteRcds(...) which uses DataInputStream methods to read a file of fixed length records containing the following four fields:

Name                      String                     10

ID                            String                     5

Balance                  Double                   8

Visits                      Short                      2

 

The method prints the file contents. It accepts a File object designating the actual file to be read. If successful, the method returns a one.  If an IOException occurs, it returns a minus one.

 

See DataOutputStream for the corresponding sample writeByte(...).method which creates this file.

 

import java.io.*;

import java.text.*;

 

    public int readByteRcds( File  f ) {

        StringBuffer sb = new StringBuffer( );

        try {

            DataInputStream dis = new DataInputStream( new BufferedInputStream( new FileInputStream( f )));

            while ( true ) {

                byte[ ] b1 = new byte[ 10 ];

                byte[ ] b2 = new byte[ 5 ];

                sb = new StringBuffer( );

                dis.readFully( b1 );                                               // read the name

                sb.append( new String( b1 ) + " " );

                dis.readFully( b2 );                                               // read the ID

                sb.append(new String( b2 ) + " " );

                double d = dis.readDouble( );                             // read the balance

                DecimalFormat df = new DecimalFormat( "$###,###.00" );

                sb.append( df.format( d ) + " " );

                short sh = dis.readShort( );                                                // read the visits

                sb.append(String.valueOf(sh));

                System.out.println(sb);                                       // print the assembled record

            }

        } catch (EOFException e) {

            return 1;

        } catch (IOException e) {

            return -1;

        }

 

 

  Compare two files.   The compareTwoFilesMethod below uses DataInputStream to compare two files of 250K or smaller, byte by byte.  It returns true if all bytes in both files match, and false if they do not.  The fully qualified String names of the files are passed in as two parameters.

 

import java.io.*;

 

public boolean compareTwoFilesMethod(String file1, String file2) {

    byte[ ] b1 = new byte[250000];

    byte[ ] b2 = new byte[250000];

    int x = 0, y = 0;

    try {

        DataInputStream dis1 = new DataInputStream(new FileInputStream(file1));

        while (true) {

            b1[x++] = dis1.readByte( );

        }

    }

    catch (EOFException e) { }

    catch (IOException ex) { }

.

     try {

        DataInputStream dis2 = new DataInputStream(new FileInputStream(file2));

        while (true) {

            b2[y++] = dis2.readByte( );

        }

    }

    catch (EOFException e) { }

    catch (IOException ex) { }

 

     if (x != y) { return false; }

     int z = x;

 

     for (int i = 0; i < z; i++) {

        if (b1[i] != b2[i]) { return false; }

    }

    return true;

    }