Serializable接口:
所谓的Serializable,就是java提供的通用数据保存和读取的接口。至于从什么地方读出来和保存到哪里去都被隐藏在函数参数的背后了。这样子,任何类型只要实现了Serializable接口,就可以被保存到文件中,或者作为数据流通过网络发送到别的地方。也可以用管道来传输到系统的其他程序中。这样子极大的简化了类的设计。只要设计一个保存一个读取功能就能解决上面说得所有问题。
当两个进程在进行远程通信时,彼此可以发送各种类型的数据。无论是何种类型的数据,都会以二进制序列的形式在网络上传送。发送方需要把这个对象转换为字节序列,才能在网络上传送;接收方则需要把字节序列再恢复为对象。
把对象转换为字节序列的过程称为对象的--->序列化。
把字节序列恢复为对象的过程称为对象的--->反序列化。
package com.enterise.test;
import java.io.Serializable;
/**
* 实体实现序列化接口
* @author Always
*
*/
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
* the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
package com.enterise.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* 将对象保存在硬盘上--读取硬盘上的对象
* @author Always
*
*/
public class MainActivity {
public static void main(String[] args){
File child = new File("e://zhou");
if(!child.exists()){
child.mkdirs();
}
File parent = new File(child, "student.tmd");
Student stu = new Student("xingming",2);
//将对象保存到本地的硬盘
try {
FileOutputStream stream = new FileOutputStream(parent);
ObjectOutputStream outStream = new ObjectOutputStream(stream);
outStream.writeObject(stu);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//从硬盘中读取对象
try {
FileInputStream stream = new FileInputStream(parent);
ObjectInputStream inStream = new ObjectInputStream(stream);
int len = 0;
byte[] by = new byte[1024];
Student student = (Student) inStream.readObject();
System.out.println("studn------>"+student.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}