// 序列化
public void serialization() throws IOException {
File File = new File("D:\\File\\ser");
OutputStream os = new FileOutputStream(File);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(list);
oos.close();
os.close();
}
//反序列化
public void Inserialization() throws IOException, ClassNotFoundException {
File File = new File("D:\\File\\ser");
InputStream is = new FileInputStream(File);
ObjectInputStream ois = new ObjectInputStream(is);
List<Student> list = (List<Students>) ois.readObject();
ois.close();
is.close();
}
其中,Students类必须implements Serializable,才能序列化;
public class Student implements Serializable{
}
集合为什么可以这么序列化?
因为集合中有两个私有的方法readObject和writeObject,这两个方法就是完成集合序列化的方法,下方附上ArrayList序列化部分的源码:
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// Write out all elements in the proper order.
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}