Java ByteBuffer Write writeShortString(ByteBuffer buffer, String s)

Here you can find the source of writeShortString(ByteBuffer buffer, String s)

Description

Write a size prefixed string where the size is stored as a 2 byte short

License

Open Source License

Parameter

Parameter Description
buffer The buffer to write to

Declaration

public static void writeShortString(ByteBuffer buffer, String s) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.*;

import java.nio.ByteBuffer;

public class Main {
    /**/*from  ww w  .  j a v a2  s. c o  m*/
     * Write a size prefixed string where the size is stored as a 2 byte
     * short
     *
     * @param buffer The buffer to write to
     */
    public static void writeShortString(ByteBuffer buffer, String s) {
        if (s == null) {
            buffer.putShort((short) -1);
        } else if (s.length() > Short.MAX_VALUE) {
            throw new IllegalArgumentException("String exceeds the maximum size of " + Short.MAX_VALUE + ".");
        } else {
            byte[] data = getBytes(s); //topic support non-ascii character
            buffer.putShort((short) data.length);
            buffer.put(data);
        }
    }

    public static byte[] getBytes(String s) {
        return getBytes(s, "UTF-8");
    }

    public static byte[] getBytes(String s, String encoding) {
        try {
            return s.getBytes(encoding);
        } catch (UnsupportedEncodingException e) {
            return s.getBytes();
        }
    }
}

Related

  1. writeLTriad(int triad, ByteBuffer bb)
  2. writeNullTerminatedString(ByteBuffer buf, String s, String encoding)
  3. writePackageName(ByteBuffer buffer, String packageName)
  4. writeRemaining(WritableByteChannel channel, ByteBuffer buffer)
  5. writeResBit15(int value, ByteBuffer toBuffer)
  6. writeSign(ByteBuffer bb)
  7. writeSignedVarint(ByteBuffer buffer, int val)
  8. writeSize(final int s, ByteBuffer buffer)
  9. writeSlice(ByteBuffer src, int number, ByteBuffer dst)