Java- Data Streams

4.Data Streams

In Previous InputStream allowed only int type, Byte Stream allowed only byte[] & CharacterStream allowed only char[] for writing data.

To work with Other Datatypes , Data streams introduced to support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) and String values. All data streams implement either the DataInput interface or the DataOutput interface

  1. DataInputStream: Used for read primitive Java data types from input stream.(readXXX() method)

  2. DataOutputStram: Used for write primitive Java data types to Output stream.(writeXXX() method)

    here XXX = primitive data types

Constructors Methods
DataInputStream (InputStream is) DataOutputStream (OutputStream os) Int read(byte b[]) Int read(byte[] b, int off, int len) Byte readByte() Int readInt() Char readchar() void write(byte b[]) void write(byte[] b, int off, int len) void writeByte(byte b) void writeInt(int i)

Example

public class DataStream {
	public static void main(String[] args) throws Exception {
 DataOutputStream dos = new DataOutputStream(new       FileOutputStream("sml.bin"));
 dos.writeInt(10);
 dos.writeUTF("Satya");
 
 DataInputStream dis = new DataInputStream(new FileInputStream("sml.bin"));
 System.out.println("Int : " + dis.readInt());
 System.out.println("String : " + dis.readUTF());
	}
}
Int : 10
String : Satya