package ei.engine.network.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import ei.engine.util.MultiPrintStream; public class Converter { /** * Converts an object to an array of bytes. * * @param object the object to convert. * @return the associated byte array. */ public static byte[] toBytes(Object object){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(object); oos.flush(); }catch(IOException ioe){ MultiPrintStream.out.println(ioe.getMessage()); } return baos.toByteArray(); } /** * Converts an array of bytes back to its constituent object. The * input array is assumed to have been created from the original object. * * @param bytes the byte array to convert. * @return the associated object. */ public static Object toObject(byte[] bytes) { Object object = null; try{ ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois= new ObjectInputStream(bais); object = ois.readObject(); }catch(IOException ioe){ MultiPrintStream.out.println(ioe.getMessage()); }catch(ClassNotFoundException cnfe){ MultiPrintStream.out.println(cnfe.getMessage()); } return object; } }