Package Cn.sjq.Serializable.java;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import Java.io.OutputStream;
/**
* Write fruit object to file
* @author SONGJQ
*
*/
public class Javaserializabledemo {
public static void Main (string[] args) throws Exception {
Defining Fruit objects
Fruit f = new Fruit ();
F.setname ("Apple");
F.settype ("001");
F.setproduction ("China");
/*
* Write fruit object F to file (fruit not serialized)
*/
Defining the output stream
OutputStream out = new FileOutputStream ("D:\\temp\\fruit.ser");
Defining an object output stream
ObjectOutputStream ObjectOutputStream = new ObjectOutputStream (out);
Objectoutputstream.writeobject (f);
Close the stream
Out.close ();
Objectoutputstream.close ();
/**
* Test Conclusion:
* 1, fruit not implemented serialization
* Exception in thread "main" java.io.NotSerializableException:cn.sjq.Serializable.java.Fruit
* Description If an object is to be written to a file, the object needs to be serialized
* 2, Fruit to realize the serialization of public class Fruit implements Serializable
* Object Fruit successfully written to the file D:\\temp\\fruit.ser
*/
/**
* Deserialization, Fruit.ser deserialized into fruit object output console
*/
InputStream in = new FileInputStream ("D:\\temp\\fruit.ser");
ObjectInputStream ObjectInputStream = new ObjectInputStream (in);
Fruit Fruit = (Fruit) objectinputstream.readobject ();
System.out.println (F.getname () + "\ T" +f.gettype () + "\ T" +f.getproduction ());
/*
* Output Result:
* Apple001china
*/
}
}
Package Cn.sjq.Serializable.java;
Import java.io.Serializable;
/**
* Java serialization: If a class implements Java serialization, this class can be used as an input and output object
* Define a Java Bean Fruit
* @author SONGJQ
*
*/
public class Fruit implements Serializable {
private String name;
Private String type;
private String production;
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String GetType () {
return type;
}
public void SetType (String type) {
This.type = type;
}
Public String getproduction () {
return production;
}
public void Setproduction (String production) {
This.production = production;
}
}
2018-07-25 period Java serialization and deserialization programming small case