26
Feb

Externalizable example in Java

Externalizable example in Java
=================================

Step 1:  Create your Externalizable custom implementation
===============================================================

package J8Externalizable;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Student1 implements Externalizable {
	private static final long serialVersionUID = 6153364603381636837L;
	
	private int id;
	private String name;

	public Student1() { }     // < =======
	
	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeInt(getId());
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		in.read();  
	}

}


Step 2: Client code
==========================


package J8Externalizable;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Client {

	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		Student1 obj = new Student1();
		obj.setId(10);
		obj.setName("Jackychan");
		
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\s1.cer"));
		oos.writeObject(obj);
		oos.close();
		
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\s1.cer"));
		Student1 s =  (Student1) ois.readObject();
		ois.close();
		
		System.out.println(s.getId()+"::"+s.getName());

	}

}


Output:
========

0::null