View RSS Feed

My Java Tips

Writing/Retriving ArrayList to disk

Rate this Entry
by , 11-01-2011 at 06:31 PM (1345 Views)
Since ArrayList implements the Serializable interface, therefore ArrayList can be serialized which means it can be persisted on the disk. Following example does exactly that.



Code example follows:

Java Code:
ArrayList arrayList = new ArrayList();
arrayList.add("Mars");
arrayList.add("Satrun");
arrayList.add("Pluto");

FileOutputStream f_out = new FileOutputStream("C:\arraylist.data");

ObjectOutputStream obj_out = new ObjectOutputStream (f_out);

obj_out.writeObject (arrayList);

System.out.println("ArrayList written on the disk.");

FileInputStream f_in = new FileInputStream("C:\arraylist.data");
ObjectInputStream obj_in = new ObjectInputStream (f_in);
ArrayList arrayList_fetched =
new ArrayList((ArrayList)obj_in.readObject());

System.out.println("ArrayList fetched from the disk.");

for(int i=0;i
System.out.println(arrayList_fetched.get(i));
Output:

ArrayList written on the disk.
ArrayList fetched from the disk.
Mars
Satrun
Pluto

Submit "Writing/Retriving ArrayList to disk" to Facebook Submit "Writing/Retriving ArrayList to disk" to Digg Submit "Writing/Retriving ArrayList to disk" to del.icio.us Submit "Writing/Retriving ArrayList to disk" to StumbleUpon Submit "Writing/Retriving ArrayList to disk" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments