Java ByteBuffer to String toString(ByteBuffer buffer, int offset, int length)

Here you can find the source of toString(ByteBuffer buffer, int offset, int length)

Description

Constructs a new String by decoding the specified subarray of bytes using the ASCII charset.

License

Open Source License

Parameter

Parameter Description
buffer the buffer to be decoded into characters offset
offset the index of the first byte to decode length
length the number of bytes to decode

Return

a string representing the region defined by the given start and length

Declaration

public static String toString(ByteBuffer buffer, int offset, int length) 

Method Source Code


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

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class Main {
    /**//from   w  ww . j a  v  a2  s . c o m
     * Constructs a new String by decoding the specified subarray of bytes using
     * the ASCII charset.
     *
     * @param buffer the buffer to be decoded into characters offset
     * @param offset the index of the first byte to decode length
     * @param length the number of bytes to decode
     * @return a string representing the region defined by the given start and
     * length
     */
    public static String toString(ByteBuffer buffer, int offset, int length) {
        if (offset < 0 || length < 0 || offset + length > buffer.limit()) {
            throw new IndexOutOfBoundsException();
        }
        int position = buffer.position();
        int limit = buffer.limit();
        buffer.position(offset);
        buffer.limit(offset + length);
        String result = StandardCharsets.US_ASCII.decode(buffer).toString();
        buffer.position(position);
        buffer.limit(limit);
        return result;
    }
}

Related

  1. toString(ByteBuffer buffer)
  2. toString(ByteBuffer buffer)
  3. toString(ByteBuffer buffer)
  4. toString(ByteBuffer buffer)
  5. toString(ByteBuffer buffer, Charset charset)
  6. toString(ByteBuffer buffer, String encoding)
  7. toString(ByteBuffer bytes)
  8. toString(ByteBuffer bytes)
  9. toString(ByteBuffer sequence)