1、概念
2、对象的序列化机制
2.1、对象流序列化字符串的过程
/**
* 序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去,使用ObjectOutStream实现
*/
@Test
public void testObjectOutStream(){
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new String("我爱你"));
oos.flush();//刷新
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos!=null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.2、对象流反序列化字符串的过程
/**
* 反序列化过程
*/
@Test
public void testInputStreamObject(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
String str = (String)obj;
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois!=null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.3、自定义Person类实现序列化与反序列化的操作
Perosn类:
public class Person implements Serializable {
private static final long serialVersionUID = 683274923094L;
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
序列化与反序列化操作:
public class ObjectInputStreamOutStreamTest {
/**
* 序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去,使用ObjectOutStream实现
*/
@Test
public void testObjectOutStream(){
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new String("我爱你"));
oos.flush();//刷新
oos.writeObject(new Person("王铭",23));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos!=null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 反序列化过程:将磁盘文件中的对象还原为内存中的一个java对象
*/
@Test
public void testInputStreamObject(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
String str = (String)obj;
Person p =(Person) ois.readObject();
System.out.println(str);
System.out.println(p);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois!=null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}