序列化:IO流层面的序列化就是将基本数据类型或者对象从内存(程序)中写入磁盘的过程,在网络或者两端进行传输
ObjectOutputStreamoos.writeObject(Object o)反序列化:将磁盘中的序列化文件读入内存(程序)中进行还原
ObjectInputStreamois.readObject()如果要传输自定义类对象,则该自定义类需要实现Serializable接口,且需要写一个
private static final long serialVersionUID = xxxL;还要保证类内部的所有属性都是可序列化的注意点:
被static和transient修饰的成员变量不能被序列化一般是用IO都不自己写,导入一些jar包,直接用
/** * 序列化 * 将程序中的对象转换成二进制文件存入磁盘中 */ @Test public void test(){ //1. 找到文件 //File file1 = new File(""); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("object.txt")); //2. 处理文件 oos.writeObject(new String("天天都敲代码")); } catch (IOException e) { e.printStackTrace(); } finally { //3. 关闭流 if(oos != null){ try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 反序列化 * 把磁盘中的文件还原成程序中的一个对象 */ @Test public void test2(){ ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("object.txt")); Object o = ois.readObject(); System.out.println(o); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if(ois != null){ try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } }