Saturday, July 13, 2013

DataInputStream vs. DataOutputStream

DataInputStream is a data input stream that lets you read primitive data types from an input stream. In contrast, DataOutputStream writes the primitive data types to an output stream.
In Java, primitive data types can be byte, integer, long, float, double, boolean, and char.

DataInputStream constructor:
-DataInputStream(FileInputStream fis)

Its Useful methods:
-readByte(byte[] barray):int
-readByte():byte
-readInt():int
-readLong():long
-readDouble():double
-readBoolean():boolean
-readChar():char
-readUTF():String

DataOutputStream constructor:
-DataOutputStream(FileOutputStream fos)

Its useful methods:
-writeByte(byte b):void
-writeBytes(String s):void
-writeInt(int i):void
-writeLong(long l):void
-writeDouble(double d):void
-writeChar(char c):void
-writeBoolean(boolean bo):void
-writeUTF(String su):void

Example:

import java.io.*;
public class Example{

public static void main(String[] args){

int[] data={12,33,33,43};
writeInteger(data, "Integers.bin");
readInteger("Integers.bin");
}

public static void writeInteger(int[] data, String src){
try{
FileOutputStream fos=new FileOutputStream(src); //create file output stream
DataOutputStream dos=new DataOutputStream(fos); //create data output stream
for(int i=0;i<data.length;i++)
dos.writeInt(data[i]); //write integers to the file
dos.flush();
dos.close();

}catch(Exception e){}

}
public static void readInteger(String src){
try{
FileInputStream fis=new FileInputStream(src); //create file input stream
DataInputStream dis=new DataInputStream(fis); //create data input stream
int x;
while((x=dis.readInt())!=-1) //read integers from the file
System.out.println(x);
dis.close();
}catch(Exception e){}

}
}

1 comment:

  1. I have found that this site is very informative, interesting and very well written. keep up the nice high quality writing Convert Word to PDF

    ReplyDelete