Modul 6 Object Persistence Dan Object
Modul 6 Object Persistence Dan Object
DASAR TEORI
1. Object Persistence
Object persistence adalah kemampuan sebuah object untuk tetap hidup
dalam sebuah sistem, tidak terpengaruh waktu dan ruang (space), bahkan apabila
aplikasi pembuat object tersebut telah dihentikan atau komputer dimatikan. Untuk
itu objek yang diinginkan supaya persistence harus disimpan secara utuh.
Penyimpanan objek secara utuh melibatkan penyimpanan struktur data yang
dimiliki oleh objek tersebut, nilai-nilai atribut yang dimilikinya, dan pemetaan
terhadap referensi ke objek lain apabila ada, sekaligus objek yang direferensikannya.
Proses itu merupakan sebuah proses yang kompleks dan rumit.
2. Object Serialization
PRAKTIKUM
import java.io.*;
import java.util.*;
// Chapter 4, Listing 5
public class SerializationDemo
{
public static void main(String args[])
{
try
{
Vector list;
// Create a buffered reader for easy input
BufferedReader reader = new BufferedReader
( new InputStreamReader ( System.in ) );
System.out.println ("Checking for
previous serialized list");
// Check to see if serialized list exists
try
{
FileInputStream fin = new
FileInputStream ("list.out");
// list
ObjectInputStream oin = new ObjectInputStream
( fin );
try
{
// Read the vector back from the
list Object obj = oin.readObject();
// Cast back to a vector
list = (Vector) obj;
}
catch (ClassCastException cce)
{
// Can't read it, create a blank
one list = new Vector();
}
catch (ClassNotFoundException cnfe)
{
// Can't read it, create a blank
one list = new Vector();
}
fin.close();
}
catch (FileNotFoundException fnfe)
{
// Create a blank vector
list = new Vector();
}
// Repeat
indefinitely for (;;)
{
// Now, display menu System.out.println
("Menu :-"); System.out.println ("1.. Add
item"); System.out.println ("2.. Delete
item");
System.out.println ("3.. List items");
// Convert to an int
int choice = Integer.parseInt (response);
switch (choice)
{
case 1 :
// Add the item to
list System.out.print
("Enter item : ");
String item = reader.readLine();
list.addElement(item);
break;
case 2 :
// Delete the item from
list System.out.print
("Enter item : ");
String deadItem =
reader.readLine();
list.removeElement(deadItem);
break;
case 3 :
// List the elements of the
list for (Enumeration e =
list.elements();
e.hasMoreElements();)
{
System.out.println
(e.nextElement());
}
break;
case 4 :
// Save list and terminate
System.out.println ("Saving
list"); FileOutputStream
fout = new FileOutputStream
( "list.out" );
ObjectOutputStream ( fout );
}
}
}
catch (IOException ioe)
{
System.err.println ("I/O error");
}
}
}
Praktikum Modul 5