Deserialization in Java

import java.io.*;
public class Person implements Serializable {
	private String firstName;
	private String lastName;
	private int age;
	public Person() {
	}
	public Person(String fn, String ln, int age1) {
		firstName = fn;
		lastName = ln;
		age = age1;
	}
	public String toString() {
		String str = firstName + "\t" + lastName + "\t" + age;
		return str;
	}
}

Download

import java.io.*;
public class Main1 {
	public void readPersons(String filename) {
		ObjectInputStream inputStream = null;
		try {
			// Construct the ObjectInputStream object
			inputStream = new ObjectInputStream(new FileInputStream(filename));
			Object obj = null;
			while ((obj = inputStream.readObject()) != null) {
				if (obj instanceof Person) {
					System.out.println(((Person) obj).toString());
				}
			}
		} catch (Exception ex) { // This exception will be caught when EOF is
									// reached
			System.out.println("End of file reached.");
		} finally {
			// Close the ObjectInputStream
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
}
public static void main(String[] args) {
	new Main1().readPersons("myFile.txt");
	}
}

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