您的位置:首页 > 移动开发 > Objective-C

IO流对象序列化与反序列化

2016-06-30 00:03 387 查看
package com.mipo.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;

/**
* ObjectInputStream和ObjectOutputStream类是用于存储和读取基本数据类型或对象的过滤流,
* 可以把Java中的对象写到数据源中,也可以把对象从数据源中还原回来
* 此二者不可序列化       static和transient修饰的成员变量,以及方法
* 		可序列化          属性(包括基本数据类型、数组、对其它对象的引用),类名
*
* 对象序列化:将对象存储到外存中或以二进制形式进行网络传输。
* 对象反序列化:从这些数据中重构一个与原始对象状态相同的对象。
*
* 序列化的好处在于,它可以将任何实现了Serializable接口的对象转换为字节数据。
* 这些数据可以保存在数据源中,以后仍可以还原为原来的对象状态,即使这些数据通过网络传输到别处也能还原回来。
* Serializable是一个空接口,当一个类声明要实现Serializable时,只是表明该类可序列化。
* @author Administrator
*
*/
public class TestSerializable {

public static void main(String[] args) {
test1();
test2();

}

//**********序列化示例**************************
public static void test1 () {
ObjectOutputStream oos = null;

try {
//创建连接到指定文件的对象输出流实例
oos = new ObjectOutputStream(new FileOutputStream("D:\\Personal\\Desktop\\IO\\File\\demo\\test1.dat"));
//把student对象序列化到文件中
oos.writeObject(new Student(101,"鸣人",22));
//刷新输出流
oos.flush();
System.out.println("序列化成功");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != oos) {
try {
oos.close();//关闭输出流实例
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

//*******************反序列化实例***************
public static void test2 () {
ObjectInputStream ois = null;
try {
//创建连接到指定文件的输入流实例
ois = new ObjectInputStream(new FileInputStream("D:\\Personal\\Desktop\\IO\\File\\demo\\test1.dat"));
//读取对象
Student stu = (Student) ois.readObject();
//输出读到的对象信息
System.out.println(stu);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (null != ois) {
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//关闭对象输入流
}
}
}
}

//创建学生类****************************************
class Student implements java.io.Serializable {
private int id;
private String name;
private transient int age;//不需要序列化的属性

public Student() {}
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
//必须重写toString方法,输出是Student [id=101, name=鸣人, age=0],否则输出对象地址
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息