Externalization in Java

import java.io.*;
public class ExternalDemo {
	public static void main(String args[]) {
		// object serialisation
		write1();
		// object deserialisation
		read1();
	}
	public static void read1() {
		try {
			Myclass ob2;
			FileInputStream fis = new FileInputStream("serial.txt");
			ObjectInputStream ois = new ObjectInputStream(fis);
			ob2 = (Myclass) ois.readObject();
			ois.close();
			System.out.println("Object2:" + ob2);
		} catch (Exception e) {
			System.out.println(e);
			System.exit(0);
		}
	}
	private static void write1() {
		try {
			Myclass ob1 = new Myclass("Hello", 7, 2.7);
			System.out.println("Object1" + ob1);
			FileOutputStream fos = new FileOutputStream("serial.txt");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(ob1);
			oos.flush();
			oos.close();
		} catch (Exception e) {
			System.out.println(e);
			System.exit(0);
		}
	}
}
class Myclass implements Externalizable {
	String s;
	int i;
	double d;
	public Myclass(String s, int i, double d) {
		this.s = s;
		this.i = i;
		this.d = d;
	}
	public String toString() {
		return "s= " + "\"" + s + "\"" + "|" + "i=" + i + "|" + "d=" + d;
	}
	public Myclass() {
		System.out.println("In the constructor");
	}
	public void writeExternal(ObjectOutput out) {
		System.out.println("In the WriteExternal");
	}
	public void readExternal(ObjectInput in) {
		System.out.println("In the ReadExternal");
	}
}

Download

Input and Output Stream in Java

Example FileOutputStream
Example FileInputStream
DataInput and Output Example
Object Serialization
Object Deserialization
Object Externalizable Example
Example java.io.File class
RandomAccessFile Example


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code