Serialization (Part 1) – Basics

Serialization means make the object transferable :

  1. between ip addresses over a network
  2. between memory addresses
  3. into a file
  4. into a database systems

Serializable interface in java provides serialization capabilities to any object type which is implement that and all of its content instances (all of its memebers). Object graph

Serializable interface is an marker interface = does’t hvae any menthod.


import java.io.Serializable;

/**
*
* @author Unknown_
*/
public class User implements Serializable {

private String username, password;

public User() {
}

public User(String username, String password) {
this.username = username;
this.password = password;
}

public void updateUsername(String username) {
System.out.println("username's changed to ... " + username);
this.username = username;
}

@Override
public String toString() {
return "Name: " + this.username + " - passwd: " + this.password;
}

public void showcontent() {
System.out.println("" + this.toString());
}

}

so far we have made this class serializable, but how we can save and persist and also reload it from our file system?

  • ObjectInputStream
  • ObjectOutputStream

by using above calsses you can just easily drop the serilized object into the input stream or fetch them from output stream without being worried about the rest of the process and the result will be provided. Check below examples:


import com.navid.practice.serialization.banking.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* we have a bank account and we want to save and then reload that into the
* object instance to see how serialization will work.
*
* @author Unknown_
*/
public class TestScenario1 {

/**
* saving objects into a file that is mentioned in the filename argument.
*
* @param ba
* @param filename
*/
public static void saveUser(User u, String filename) {

try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(Paths.get(filename), StandardOpenOption.CREATE))) {

out.writeObject(u);

} catch (IOException ex) {
Logger.getLogger(TestScenario1.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
}
}

/**
* reading the object from the file mentioned as filename.
*
* @param filename
* @return
*/
public static User reloadUser(String filename) {

User u = null;
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(Paths.get(filename), StandardOpenOption.READ))) {
u = (User) in.readObject();

} catch (IOException ex) {
Logger.getLogger(TestScenario1.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(TestScenario1.class.getName()).log(Level.SEVERE, null, ex);
}
return u;
}

public static void main(String[] args) {

User u = new User("MyOldUserName", "myPasswd1");
u.showcontent();
u.updateUsername("myNewUsername");
u.showcontent();

System.out.println("Saving Object ... ");
saveUser(u, "myAccounts.dat");
System.out.println("Reloading Object ... ");
reloadUser("myAccounts.dat").showcontent();

}

}

output will be something like this …

run:
Name: MyOldUserName - passwd: myPasswd1
username's changed to ... myNewUsername
Name: myNewUsername - passwd: myPasswd1
Saving Object ... 
Reloading Object ... 
Name: myNewUsername - passwd: myPasswd1
BUILD SUCCESSFUL (total time: 0 seconds)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s