About java objects in serialized

java object serialization mechanism, there are two general purposes:

1. The need to save the state of the object to a file, and then be able to reconstruct the object by reading the state of the object, the recovery program state

2. Use a socket program transfer object on the network, it is very useful.

We will make the class serialized by class implements java.io.Serializable interface. This interface is a manufacturer (marker) interfaces. That is, for it to achieve its class, the interface is not required to implement any method. It is mainly used to inform the Java Virtual Machine (JVM), an object needs to be serialized.

For this, we need to clear a few points:

1. Not all classes can be serialized in the cmd, we enter serialver java.net.socket, can be obtained if the socket can be serialized information, in fact, can not be serialized socket.

There are many 2.java base class has achieved the serializable interface, such as string, vector and so on. But such hashtable does not implement serializable interface.

The main object class read or write two streams: ObjectOutputStream and ObjectInputStream. ObjectOutputStream writes writeObject method for providing the output stream object, ObjectInputStream readObject provided a method of reading object from the input stream. Objects using these methods must have been serialized. In other words, you must have realized Serializable. If you want writeobject a hashtable object, then, you will be an exception.

Below is an example:

import java.io. *;

public class testser implements Serializable {

public int ii;

testser () {

}

testser( int param ) {

ii = stop;

}

}

testser is a class that implements the serializable interface.

This sequence of reading and writing through the classes:

import java.io. *;

public class Ser {

private static String datafile;

datafile="ser.data";

public static void main( String[] argv ) {

System.out.println( "Java Serialization Demo." );

Serdal date;

try {

ObjectInputStream in = new ObjectInputStream( new FileInputStream( datafile ));

data = (SerData) in.readObject();

in.close();

}

catch (Exception e) {

data = new testser();

}

System.out.println( "Original data: ii = " + data.ii );

data.ii ++;

try {

ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( datafile ) );

out.writeObject( data );

out.flush();

out.close();

}

catch (Exception e) {

System.out.println( e );

}

}

}

There can be passed through a socket serialized object, probably similar, not repeat them.

Guess you like

Origin www.cnblogs.com/long2050/p/12173317.html