Java-Reading Writing Primitive Data Types

Reading Writing Primitive Data Types

The basic reading and writing streams provide read/write methods that can only be used for reading/writing bytes or characters. If we want to read/write the primitive data types such as integers and doubles, we can use filter classes as wrappers on existing reading and writing streams to filter data in the original stream. The two filter classes used for creating “data streams” for handling primitive types are DatalnputStream and DataOutputStream.

The following program demonstrates the use of data streams for reading and writing primitive data types. The program first creates “data.da” file and then writes a few primitive data types into it using DataOutputStream. At the end of writing, the streams are closed. The program also creates a DataInputStream, and connects it to “data.da” file. It then reads data from the file and displays them on the screen. Finally, it closes the streams.

Program

final

Program Source

import java.io.FileOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.IOException;

class Javaapp {
    
    public static void main(String[] args) throws IOException {
        
        FileOutputStream fos = new FileOutputStream("data.da");
        DataOutputStream dos = new DataOutputStream(fos);
        dos.writeInt(50000);
        dos.writeShort(2500);
        dos.writeByte(120);
        dos.close();
        fos.close();
        
        FileInputStream fis = new FileInputStream("data.da");
        DataInputStream dis = new DataInputStream(fis);
        System.out.println(dis.readInt());
        System.out.println(dis.readShort());
        System.out.println(dis.readByte());
        dis.close();
        fis.close();        
    }
}

Leave a Comment