Java- Object Streams

5.Object Streams

Just as data streams support I/O of primitive data types, object streams support I/O of objects. Here we have to know about Serialization.

| ObjectOutputStream(OutputStream out) void writeObject(Object obj) | ObjectInputStream(InputStream in) Object readObject() | |———————————————————————–|———————————————————–|

1.Serialization

Serialization is the process of saving the state of the object permanently in the form of a file/byte stream. To develop serialization program, follow below steps

Steps to implement Serialization

  1. Choose the appropriate class name whose object is participating in serialization.

  2. This class must implement java.io.Serializable (this interface does not contain any abstract methods and such type of interface is known as marker or tagged interface)

  3. Choose data members, writer setters & getters

  4. Choose Serializable subclass

  5. Choose the file name and open it into write mode with the help of FileOutputStream class

  6. Pass OutputStream object to ObjectOutputStream(out) constructor to write object data at a time

  7. use oos.writeObject(student) method to write Student Object data

Example

class Student implements Serializable {
	// Exception in thread "main" java.io.NotSerializableException: io.Student if it wont implenet Serializable
	private int sno;
	private String name;
	private String addr;
	 
	//Seeters & getters setName,SetAddr methods
}
public class Serialization {
public static void main(String[] args) throws  Exception {
	Student student = new Student();
	student.setSno(101);
	student.setName("Satya Kaveti");
	student.setAddr("VIJAYAWADA");
	
	FileOutputStream fos = new FileOutputStream("student.txt");
	ObjectOutputStream oos = new ObjectOutputStream(fos);
	oos.writeObject(student);	
}
}
//data saved in student.txt
’ sr 
io.StudentÓÞ®(¦°¦  I  snoL  addrt Ljava/lang/String;L  nameq ~ xp   et 
VIJAYAWADAt

2.Deserialization

De-serialization is a process of retrieve the data from the file in the form of object.

Steps

  1. Choose the file name and open it into read mode with the help of FileInputStream class

  2. Pass InputStream object to ObjectInputStream(in) constructor to read object data at a time

  3. use ois.readObject() method to get Student Object

Example

public class Deserialization {
	public static void main(String[] args) throws Exception{
 FileInputStream fis = new FileInputStream("student.txt");
 ObjectInputStream ois = new ObjectInputStream(fis);
 Student st = (Student)ois.readObject();
 System.out.println(st.getSno());
 System.out.println(st.getName());
 System.out.println(st.getAddr()); 
	}
}
101
Satya Kaveti
VIJAYAWADA

If we use above process to implement serialization, all the data members will participate in Sterilization process. If you want to use selected data members for serialization use Transient keyword

Transient Keyword

In order to avoid the variable from the serialization process, make that variable declaration as transient i.e., transient variables never participate in serialization process.

Example

class Student implements Serializable {	 
	private transient int sno;
	private transient String name;
	private String addr;
}

public class TransientExample {
	public static void main(String[] args) throws  Exception {
 Student student = new Student();
 student.setSno(101);
 student.setName("Satya Kaveti");
 student.setAddr("VIJAYAWADA");
 
 FileOutputStream fos = new FileOutputStream("student.txt");
 ObjectOutputStream oos = new ObjectOutputStream(fos);
 oos.writeObject(student);	
 
 FileInputStream fis = new FileInputStream("student.txt");
 ObjectInputStream ois = new ObjectInputStream(fis);
 Student st = (Student)ois.readObject();
 System.out.println(st.getSno());
 System.out.println(st.getName());
 System.out.println(st.getAddr()); 
	}
}
0
null
VIJAYAWADA

Printing of sno,name returns 0,null because values of sno,name was not serialized.

3. Externalization

The default serialize object is heavy weight & having lots of attributes and properties, that you do want to serialize for any reason (e.g. they always been assigned default values), you get heavy object to process and send more bytes over network which may be costly on some cases.

To customize your serialization mechanism, we can use Externalization.Externalizable interface extends Serializable interface. If you implement this interface, then you need to override following methods

public void readExternal(ObjectInput arg0) throws IOException,
public void writeExternal(ObjectOutput arg0) throws IOException

Example : Im a Student , I don’t want to save my GF data.

class Student implements Externalizable {

	private int sno;
	private String name;
	// I dont want save my GF data
	private String girlFriend;
// getters & setters

	public Student(int sno, String name) {
 this.sno = sno;
 this.name = name;
	}

	@Override
	public void readExternal(ObjectInput input) throws IOException, ClassNotFoundException {
 sno = input.readInt();
 name = input.readUTF();// String
	}

	@Override
	public void writeExternal(ObjectOutput output) throws IOException {
 output.writeInt(sno);
 output.writeUTF(name);
	}

	@Override
	public String toString() {
 return "Student [sno=" + sno + ", name=" + name + ", girlFriend=" + girlFriend + "]";
	}

}

public class Test {
	public static void main(String args[]) throws Exception {
 // Writing data
 FileOutputStream fos = new FileOutputStream("student.txt");
 ObjectOutputStream oos = new ObjectOutputStream(fos);
 oos.writeObject(new Student(101, "Satya"));

 // Reading data
 FileInputStream fis = new FileInputStream("student.txt");
 ObjectInputStream ois = new ObjectInputStream(fis);
 Student s = (Student) ois.readObject();
 System.out.println(s.toString());
	}
}
Student [sno=101, name=Satya, girlFriend=null]

StreamTokenizer

StreamTokenizer class (java.io.StreamTokenizer) can tokenize the characters read from a Reader into tokens. For instance, in the string “Mary had a little lamb” each word is a separate token

StreamTokenizer streamTokenizer = new StreamTokenizer(
        new StringReader("Mary had 1 little lamb..."));

while(streamTokenizer.nextToken() != StreamTokenizer.TT_EOF){

    if(streamTokenizer.ttype == StreamTokenizer.TT_WORD) {
        System.out.println(streamTokenizer.sval);
    } else if(streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) {
        System.out.println(streamTokenizer.nval);
    } else if(streamTokenizer.ttype == StreamTokenizer.TT_EOL) {
        System.out.println();
    }
}
streamTokenizer.close();

printf and format Methods

The java.io package includes a PrintStream class that has two formatting methods. format and printf

public PrintStream format (String format, Object... args)

System.out.format("The value of " + "the float variable is " +
     "%f, while the value of the " + "integer variable is %d, " +
     "and the string is %s", floatVar, intVar, stringVar);