package pack.java.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class A implements Serializable{
private String name ="My Name Is Class A";
private B b;
public String getName() {
return name;
}
public void setName(String a) {
this.name = a;
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
public A(){
this.b = new B();
}
public String show(){
return "a.toString"+name+","+b.getName();
}
}
class B implements Serializable{
private String name="My Name is B";
private A a;
public B() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
}
public class SerializableDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SerializableDemo serializableDemo=new SerializableDemo();
//序列化方法;
serializableDemo.writeSerializable();
//反序列化方法;
serializableDemo.readSerializable();
}
/***
* 序列化;
* 把对象写入文件中;
*
*/
private void writeSerializable(){
ObjectOutputStream objectOutputStream=null;
try {
FileOutputStream fileOutputStream=new FileOutputStream(new File("//192.168.1.11/abapfiles/object.txt"));
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
A a=new A();
objectOutputStream.writeObject(a);
System.out.println("write show:"+a.show());
objectOutputStream.flush();
objectOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/***
* 反序列化;
* 从文件读取对象;
*
*/
private void readSerializable(){
ObjectInputStream objectInputStream=null;
try {
FileInputStream fileInputStream=new FileInputStream(new File("//192.168.1.11/abapfiles/object.txt"));
try {
objectInputStream = new ObjectInputStream(fileInputStream);
try {
A a=(A)objectInputStream.readObject();
System.out.println(a.show());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}