Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1. write an essay about what is Serialization, define some cases and select appropiate
- Serialization scenario to solve those case, explain why.
- Serialization adalah mekanisme mengubah keadaan suatu objek menjad
- aliran byte.
- 1. Untuk menyimpan / mempertahankan status suatu objek
- 2. Untuk melakukan perjalanan objek di jaringan.
- 2. write a simple code to show Serialization in action by implementing you cases above.
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- public class reliasasi implements java.io.Serializable
- {
- public int a;
- public String b;
- // Default Constructor
- public reliasasi(int a, String b)
- {
- this.a = a;
- this.b = b;
- }
- }
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- class test
- {
- public static void main(String[] args)
- {
- reliasasi k = new reliasasi(1, "Rahmad");
- String filenama = "file.ser";
- // Serialization
- try
- {
- // Saving of object in a file
- FileOutputStream file = new FileOutputStream(filenama);
- ObjectOutputStream out = new ObjectOutputStream(file);
- // Method for serialization of object
- out.writeObject(k);
- out.close();
- file.close();
- System.out.println("Object has been serialized");
- }
- catch(IOException ex)
- {
- System.out.println("IOException is caught");
- }
- reliasasi k1 = null;
- // Deserialzation
- try
- {
- // Reading the object from a file
- FileInputStream file = new FileInputStream(filenama);
- ObjectInputStream in = new ObjectInputStream(file);
- // Method for deserialization of object
- k1 = (reliasasi) in.readObject();
- in.close();
- file.close();
- System.out.println("Object has been deserialized");
- System.out.println("Result a = " + k1.a);
- System.out.println("Result b = " + k1.b);
- }
- catch (IOException ex)
- {
- System.out.println("IOException is caught");
- }
- catch (ClassNotFoundException ex)
- {
- System.out.println("ClassNotFoundException is caught");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment