writing and reading data in file using DataInputStream and DataOutputStream in java with examples

Updated:06/feb/2022 by Computer Hope

Here we are creating object of DataOutputStream for writing file and for printing we use DataInputStream
Refer below code for more understanding

import java.io.*;
import java.util.*;
class Emp
{
	private int age;
	private String name;
	private double sal;
	
	public void get()
	{
		Scanner kb=new Scanner(System.in);
		System.out.println("enter age name and sal");
		age=kb.nextInt();
		name=kb.next();
		sal=kb.nextDouble();
	}
	public void show()
	{
		System.out.println(age);
		System.out.println(name);
		System.out.println(sal);
	}
	public void writeInFile()
	{
		try
		{
			DataOutputStream dout;
			dout=new DataOutputStream(new FileOutputStream("D:/DeveloperFile.dat"));
			dout.writeInt(age);
			dout.writeUTF(name);
			dout.writeDouble(sal);
			dout.close();
		}
		catch(Exception ex)
		{
			System.out.println("Error in writing "+ex);
			System.exit(0);
		}
	}
	public void readFromFile()
	{
		try
		{
			DataInputStream din;
			din=new DataInputStream(new FileInputStream("D:/DeveloperFile.dat"));
			age=din.readInt();
			name=din.readUTF();
			sal=din.readDouble();
			din.close();
		}
		catch(Exception ex)
		{
			System.out.println("Error in reading "+ex);
			System.exit(0);
		}
	}
}

class ExampleReadWrite
{
	public static void main(String args[]) 
{
    Emp E=new Emp();
    E.get();
    E.writeInFile();
    
    Emp F=new Emp();
    F.readFromFile();
    F.show();
}
}