package SerializeDemo;
import java.io.*;
public class Fruit implements Serializable {
int size = 42;
Fruit(String s) {
System.out.println("fruit...");
}
Fruit() {
System.out.println("fruit...");
}
}
package SerializeDemo;
import java.io.*;
public class Apple extends Fruit{
int as = 3;
private transient String s = "I'm not serializable..." ;
public Apple() {
// super("aa");
System.out.println("the as is :" + as);
}
public void writeObject(ObjectOutputStream os) {
try {
os.defaultWriteObject();
os.writeObject(s);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("invoke the writeObject...");
}
public void readObject(ObjectInputStream os) {
System.out.println("invoke the readObject...");
try {
os.defaultReadObject();
// s = (String)os.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Apple readApple(FileInputStream is) {
Apple a = null;
try {
ObjectInputStream ois = new ObjectInputStream(is);
a = (Apple)ois.readObject();
ois.close();
}
catch(Exception e) {
e.printStackTrace();
}
return a;
}
public void saveApple(FileOutputStream os,Object obj) {
try {
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(obj);
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("Apple.txt");
FileInputStream fis = new FileInputStream("Apple.txt");
Apple a = new Apple();
a.size = 20; //super original 42
a.as = 20;
a.saveApple(fos, a);
Apple b = a.readApple(fis);
// System.out.println("b.size is:"+b.size+"\tb.as is:"+b.as);
System.out.println("b.size is:"+b.size+"\tb.as is:"+b.as+"\tb.food is:"+b.s);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
序列化心得
最新推荐文章于 2022-03-01 21:17:56 发布