map、list深拷贝同一方法:
public static Object deepCopy(Object src) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
Object dest = in.readObject();
return dest;
}
注意:泛型类是个实体类时,必须先序列化(implements Serializable)
持久化数据(写入文件)
public void copyMap( Object src) throws IOException {
FileOutputStream fos=new FileOutputStream("obj.txt",false);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(src);
oos.close();
}
读取数据(读取文件)
public Object readObject() throws IOException, ClassNotFoundException {
FileInputStream fis=new FileInputStream("obj.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Object maps= ois.readObject();
ois.close();
return maps;
}