Home  >  Core Java

Externalization Example in Java

By Arvind Rai, May 02, 2019
Java class can be saved into byte stream using externalization. To get complete control on class persistence as byte stream, java provides externalization. java.io.Externalizable interface declares two method i.e. writeExternal and readExternal. A class which needs to be externalize, must implement Externalizable interface and has to define two method readExternal and writeExternal. Find the example.
User.java
package com.concretepage;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class User implements Externalizable {
	private String userName;
	private int age;
	
	public User(){}
	
	public User(String userName,int age){
		this.userName= userName;
		this.age=age;
	}
	@Override
	public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
		userName=(String) in.readObject();
		age=in.readInt();
		
	}
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeObject(userName);
		out.writeInt(age);
	}
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
In the class implementing Externalizable, there must a no argument constructor.
ConcreteMain.java
package com.concretepage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ConcreteMain {
   public static void main(String... args) throws Exception, IOException{
	   
	   File f= new File("ext.txt");
	   User u= new User("Atul",20);
	   
	   ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));  
       out.writeObject(u);  
      
       ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
       u=(User)in.readObject();
       
       System.out.println("After  de externalizing user name: " +u.getUserName()+" and age is:"+u.getAge());   
   }
}
Only those fields will be persisted as byte stream which will be saved by writeExternal method. Other field in the class will not be externalized. So by Externalizable interface java developer has complete control on java class persistence.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us