首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

怎么序列化对象数组

2013-07-16 
如何序列化对象数组?偶一个对象,已经实现了Serializable现在偶想对这个对象的数组序列化,该怎么办?[解决办

如何序列化对象数组?
偶一个对象,已经实现了Serializable
现在偶想对这个对象的数组序列化,该怎么办?
[解决办法]



//实现接口
@SuppressWarnings("serial")
public class Person implements Serializable {
    private int id;
    private String name;

    public Person() {
    }

    public Person(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


2.序列化转为数组

public class SerializeUtil {
    /**
     * 序列化
     * 
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);


            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {

        }
        return null;
    }


热点排行