Converts the contents of the specified ByteBuffer to a string, which is formatted similarly to the output of the Arrays#toString() method. - Java java.nio

Java examples for java.nio:ByteBuffer Convert

Description

Converts the contents of the specified ByteBuffer to a string, which is formatted similarly to the output of the Arrays#toString() method.

Demo Code


//package com.java2s;
import java.nio.ByteBuffer;

public class Main {
    /**//from  w  ww  .jav  a  2 s . c  o  m
     * Converts the contents of the specified {@link ByteBuffer} 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("[");

        int limit = buffer.limit();
        for (int index = 0; index < limit; index++) {
            String hex = Integer.toHexString(buffer.get() & 0xFF)
                    .toUpperCase();
            if (hex.length() == 1) {
                hex = "0" + hex;
            }

            builder.append("0x").append(hex);
            if (index != limit - 1) {
                builder.append(", ");
            }
        }

        builder.append("]");
        return builder.toString();
    }
}

Related Tutorials