public static void writeString( String s, ByteBuffer buffer ) throws IOException {
        if (s == null) {
            // Write that it's 0.
            buffer.put((byte)0);
            return;
        }
        byte[] stringBytes = s.getBytes("UTF-8");
        int bufferLength = stringBytes.length;

        try {
            if (bufferLength <= Byte.MAX_VALUE) {
                buffer.put((byte)1);
                buffer.put((byte)bufferLength);
            } else if (bufferLength <= Short.MAX_VALUE) {
                buffer.put((byte)2);
                buffer.putShort((short)bufferLength);
            } else {
                buffer.put((byte)3);
                buffer.putInt(bufferLength);
            }
            buffer.put(stringBytes);
        }
        catch (BufferOverflowException e) {
            e.printStackTrace();
        }    
    }
String serializer.

@author Lars Wesselius, Paul Speed
jme3-networking/src/main/java/com/jme3/network/serializing/serializers/StringSerializer.java