Here you can find the source of putObject(final ByteBuffer buffer, Serializable o)
public static void putObject(final ByteBuffer buffer, Serializable o)
//package com.java2s; /* *********************************************************************** * * project: org.matsim.*/*from w w w . ja v a2 s .co m*/ * ByteBufferUtils.java * * * *********************************************************************** * * * * copyright : (C) 2009 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.ByteBuffer; public class Main { /** * Writes the given Serializable to the ByteBuffer. First writes the length of the Serializable as int, * then writes the single bytes of the serialized object. The ByteBuffer's position is incremented according * to the length of the Serializable. * */ public static void putObject(final ByteBuffer buffer, Serializable o) { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { try (ObjectOutput oout = new ObjectOutputStream(bos)) { oout.writeObject(o); byte[] laneBytes = bos.toByteArray(); buffer.putInt(laneBytes.length); for (int i = 0; i < laneBytes.length; i++) { buffer.put(laneBytes[i]); } } } catch (IOException e) { e.printStackTrace(); } } }