Java对象数组序列化与反序列化
2014-12-05 22:56
204 查看
先创建一个Java Bean
一般都是直接把一个对象序列化,如果我们有多个同一个类的对象,那么可以将这多个对象存进一个数组中,这个数组可以时静态数组也可以是动态数组,因为数组本身也是一个对象,将这个数组对象进行序列化,最后反序列化的时候也将得到一个数组对象。
/**一个low的Java Bean*/ public class Box implements Serializable{ private int width; private int height; public Box(){ } public Box(int width,int height){ this.width = width; this.height = height; } public void setWidth(int width){ this.width = width; } public void setHeight(int height){ this.height = height; } public int getWidth(){ return width; } public int getHeight(){ return height; } }
一般都是直接把一个对象序列化,如果我们有多个同一个类的对象,那么可以将这多个对象存进一个数组中,这个数组可以时静态数组也可以是动态数组,因为数组本身也是一个对象,将这个数组对象进行序列化,最后反序列化的时候也将得到一个数组对象。
public class SerializaToFlatFile { public static void main(String[] args) throws Exception { SerializaToFlatFile ser = new SerializaToFlatFile(); // 将Box对象数组存进动态数组ArrayList中 ArrayList array = new ArrayList(); Box boxOne = new Box(816, 523); Box boxTwo = new Box(823, 324); Box boxThree = new Box(111, 222); array.add(boxOne); array.add(boxTwo); array.add(boxThree); // 序列化 ser(array); // 反序列化 array = dSer(); // 反序列化后的处理 printObj(array); } /** 序列化 */ public static void ser(Object object) throws Exception { FileOutputStream fos = new FileOutputStream("foo.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object); oos.flush(); oos.close(); } /** 反序列化 */ public static ArrayList dSer() throws Exception { FileInputStream fis = new FileInputStream("foo.ser"); ObjectInputStream ois = new ObjectInputStream(fis); ArrayList array = (ArrayList) ois.readObject(); return array; } /** 反序列化后的处理 */ public static void printObj(ArrayList array) { for (int i = 0; i < array.size(); i++) { System.out.println("width = " + ((Box) array.get(i)).getWidth() + "\r\n" + "height = " + ((Box) array.get(i)).getHeight()); } } }
相关文章推荐
- Java对象序列化(整理篇)
- Java下利用Jackson进行JSON解析和序列化示例
- JAVA的对象序列化(转自sjh1106djc的专栏)
- Java中如何将XML对象反序列化
- 通过socket连接传递java对象(对象序列化)
- Java 中对象的序列化技术
- Serializable java序列化
- Java学习之对象序列化(二)
- 关于 Ajax 的 Java 对象序列化 及获得数据后如何展现出来
- java对象序列化学习笔记
- java对象序列化学习笔记(z)
- java对象序列化学习笔记
- JAVA的对象序列化
- Java对象序列化
- java对象序列化学习笔记
- 将java的对象序列化成文件,并从文件中反序列化。
- 看JAVA序列化的性能 -- 一个简单的例子
- java对象序列化学习笔记
- RoyalAjax(三),Java对象的序列化
- 通过socket连接传递java对象(对象序列化