Java Serializable convert to ByteBuffer
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.ByteBuffer; public class Main { public static void main(String[] argv) throws Exception { ByteBuffer buf = toBuffer("demo2s.com"); System.out.println(buf);/*from w w w . j a v a 2 s . c o m*/ } /** * Convert a serializable object to buffer. * * @param obj * @return * @throws IOException */ public static ByteBuffer toBuffer(Serializable obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.flush(); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); oos.close(); baos.close(); return buffer; } }