Google

Tuesday, February 3, 2009

Object Serialization and ArrayList

//Human class
import java.io.Serializable;


public class Human implements Serializable{
private String firstname;
private int age;

public void setFirstname(String fn){
firstname=fn;
}
public void setAge(int a){
age=a;
}
public String getFirstname(){
return firstname;
}
public int getAge(){
return age;
}
}


//Main class
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class Practice {

public static void main(String[] args) throws IOException {
ArrayList hList = new ArrayList();
Human h = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
FileOutputStream fos = null;
ObjectOutputStream oos = null;

Scanner in = new Scanner(System.in);
fos = new FileOutputStream("human.txt");
oos = new ObjectOutputStream(fos);

for (int i = 0; i <>
h=new Human();
System.out.println("Enter firstname:");
h.setFirstname(in.nextLine());
System.out.println("Enter age:");
h.setAge(Integer.parseInt(in.nextLine()));
hList.add(h);
}
for(int i=0;i
oos.writeObject(hList.get(i));
}
oos.close();
fos.close();


fis = new FileInputStream("human.txt");
ois = new ObjectInputStream(fis);
hList.clear();
try {
while (true) {
hList.add((Human) ois.readObject());
}
} catch (Exception e) {

ois.close();
fis.close();
}
for(Human j:hList){
System.out.println(j.getFirstname() + " : " +j.getAge());
}

}
}