Java ByteBuffer to String getString(ByteBuffer buf)

Here you can find the source of getString(ByteBuffer buf)

Description

get String

License

Open Source License

Declaration

public static String getString(ByteBuffer buf) 

Method Source Code

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

import java.nio.ByteBuffer;

public class Main {
    public static String getString(ByteBuffer buf) {
        StringBuilder bldr = new StringBuilder();
        int b;/*from w w w . j  ava  2s  .  c  om*/
        while ((b = (buf.get() & 0xFF)) != 0) {
            bldr.append((char) b);
        }
        return bldr.toString();
    }

    /**
     * Converts the contents of the specified byte buffer to a string, which is
     * formatted similarly to the output of the {@link Arrays#toString()}
     * method.
     * @param buffer The buffer.
     * @return The string.
     */
    public static String toString(ByteBuffer buffer) {
        StringBuilder builder = new StringBuilder("[");
        for (int i = 0; i < buffer.limit(); i++) {
            String hex = Integer.toHexString(buffer.get(i) & 0xFF)
                    .toUpperCase();
            if (hex.length() == 1)
                hex = "0" + hex;

            builder.append("0x").append(hex);
            if (i != buffer.limit() - 1) {
                builder.append(", ");
            }
        }
        builder.append("]");
        return builder.toString();
    }
}

Related

  1. getStr(ByteBuffer buff)
  2. getString(@Nonnull final ByteBuffer src)
  3. getString(ByteBuffer bb)
  4. getString(ByteBuffer buf)
  5. getString(ByteBuffer buf)
  6. getString(ByteBuffer buf, Charset encoding)
  7. getString(ByteBuffer buf, int length, String charsetName)
  8. getString(ByteBuffer buffer)
  9. getString(ByteBuffer buffer)