Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

import java.io.

Serializable;

public class Employee implements Comparable<Employee>,Serializable


{
int id;
String name;
double sal;
public Employee(int id, String name, double sal) {
super();
this.id = id;
this.name = name;
this.sal = sal;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", sal=" + sal + "]";
}
@Override
public int compareTo(Employee e)
{
return ((Integer)id).compareTo(e.id);
}

}
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
import java.util.TreeSet;

public class MainStore {


public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
TreeSet<Employee> emps=new TreeSet<Employee>();
do {
System.out.println("enter the id name and salary of an employee:
");
int id=sc.nextInt();
String name=sc.next();
double sal=sc.nextDouble();
Employee emp= new Employee(id,name,sal);
emps.add(emp);
System.out.println("do you have more employees");
String res=sc.next();
if(res.equalsIgnoreCase("no"))
break;
}while(true);

System.out.println("user entred Employees: ");


for (Employee emp : emps) {
System.out.println(emp);
}
//serialization
FileOutputStream fout=null;
ObjectOutputStream out=null;
try {
fout= new
FileOutputStream("E://myfolder//myemps.txt");
out= new ObjectOutputStream(fout);
out.writeObject(emps);
out.flush();
fout.flush();
System.out.println("successfully wrten the Object");

}catch (Exception e)
{
System.out.println(e);
}
finally {
try {
fout.close();
out.close();
}catch (Exception e) {
System.out.println(e);
}
}
}
}
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Iterator;
import java.util.TreeSet;

public class MainRead


{
public static void main(String[] args) throws Exception
{
//de-serialization
FileInputStream fin= new
FileInputStream("E://myfolder//myemps.txt");
ObjectInputStream in=new ObjectInputStream(fin);

Object obj=in.readObject();

TreeSet<Employee> ts=(TreeSet<Employee>)obj;

Iterator<Employee> itr=ts.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

You might also like