serialize and unserialize Object - Java File Path IO

Java examples for File Path IO:Serialization

Description

serialize and unserialize Object

Demo Code



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SerializeUtil implements Serializable {

    private static final long serialVersionUID = -8580531504951321703L;

    private static final Logger logger = LoggerFactory
            .getLogger(SerializeUtil.class);


    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {/*from w w  w. j a  v  a  2s.  c  o  m*/
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }

    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }
    public static void main(String[] args) {

    }
}

Related Tutorials