本文共 2280 字,大约阅读时间需要 7 分钟。
编写项目时,自己创建序列化和反序列化工具类:
import java.io.*;/** *文件读写的工具类:方法要静态 */public class IOUtil { /** * 从指定文件中读数据 * @param fileName * @return * @throws IOException */ public static Object readFile(String fileName) throws IOException { FileInputStream fileInputStream = new FileInputStream(fileName); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); Object o = null; try { o = objectInputStream.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return o; } /** * 写入数据到指定文件 */ public static void writeFile(Object obj,String fileName) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(fileName); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(obj); }}
public class Student implements Externalizable { private String stuNum; private transient String stuName; private transient ListteacherList; ......
public class Student implements Externalizable { private String stuNum; private static String stuName; private ListteacherList; ......
public class Student implements Serializable { private String stuNum; private String stuName; private ListteacherList;private void writeObject(ObjectOutputStream objOut) throws IOException { System.out.println("writeObject-----------"); objOut.writeObject(stuNum); objOut.writeObject(stuName); } private void readObject(ObjectInputStream objIn) throws IOException, ClassNotFoundException { System.out.println("readObject-----------"); stuNum = (String) objIn.readObject(); stuName = (String) objIn.readObject(); }
4、Externalizable接口----可实现部分属性的序列化(不常用)
转载地址:http://rhlai.baihongyu.com/