Serialization Example

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 Main 
{
public void writePersons(String filename) 
{
ObjectOutputStream outputStream = null;
try {
//Construct the LineNumberReader object
outputStream = new ObjectOutputStream(
		new FileOutputStream(filename,true));

Person person = new Person("suman","kumar",20);
outputStream.writeObject(person);

person = new Person("sumit","singh",25);
outputStream.writeObject(person);
} 
catch (Exception ex) 
{
ex.printStackTrace();
} 
finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

public static void main(String[] args) {
new Main().writePersons("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