Monday, 6 February 2017

DATAINPUTSTREAM AND DATAOUTPUTSTREAM IN JAVA

These classes are used to read and write the data as primitive type from the underlying InputStream and OutputStream. These classes have special methods to perform reading and writing operation as primitive data type.

DataInputStream – It is a sub class of FilterInputStream and DataInput interface. It implements methods from the DataInput interface for reading bytes from a BinaryInputStream and convert them into corresponding java primitive types.

DataOutputStream – It is a subclass of FilterOutputStream and DataOutput interface. It implements methods from the DataOutput interface for converting data from any of the java primitive types to a stream of bytes and writing these bytes to a BinaryOutputStream.

Example – The method of writing data as primitive type using DataOutputStream class.
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataOutput {
          public static void main(String[] args) throws IOException {
                   FileOutputStream fos = new FileOutputStream("xyz.txt");
                   DataOutputStream dos = new DataOutputStream(fos);
                   dos.writeInt(96);
                   dos.writeFloat(3.14f);
                   dos.writeChar('L');
                   dos.writeBoolean(true);
                   dos.writeByte(10);
                   dos.writeUTF("CMP");
                   System.out.println("Data written to file");
                   dos.close();
          }
}

Output –
Data written to file

Note – After compilation and execution in current working directory, file size is 19 bytes. It is an addition of all primitive types.
(int+float+char+boolean+string) = (4+4+2+1+2+6)

Example – Reading data as primitive type using DataInputStream class
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class DataInput {
          public static void main(String[] args) throws IOException {
                   FileInputStream fis = new FileInputStream("xyz.txt");
                   DataInputStream dis = new DataInputStream(fis);
                   int i = dis.readInt();
                   float f = dis.readFloat();
                   boolean b = dis.readBoolean();
                   char c = dis.readChar();
                   String s = dis.readUTF();
                   System.out.println(i);
                   System.out.println(f);
                   System.out.println(b);
                   System.out.println(c);
                   System.out.println(s);
                   dis.close();
          }
}

Output –
Exception in thread "main" java.io.EOFException


Limitations of DIS and DOS –
Using DIS and DOS class we cannot read and write objects from persistence media. They have the capability only to read data up to primitive data types. To read and write objects we must use ObjectInputStream and ObjectOutputStream

No comments:

Post a Comment