您的位置:首页 > 编程语言 > Java开发

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());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息