Java ByteBuffer to String bytesToString(ByteBuffer buf, int off, int len)

Here you can find the source of bytesToString(ByteBuffer buf, int off, int len)

Description

Convert from bytes to a string.

License

Open Source License

Parameter

Parameter Description
buf A byte buffer to get the bytes from. Should be ascii or latin1.
off The offset into buf.
len The length to get.

Return

A string.

Declaration

public static String bytesToString(ByteBuffer buf, int off, int len) 

Method Source Code

//package com.java2s;
/*//from   w  w w . j a  v a2s  .c  o m
 * Copyright (C) 2006 Steve Ratcliffe
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 * 
 * Author: Steve Ratcliffe
 * Create date: 03-Dec-2006
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Convert from bytes to a string.  Only to be used when the character set
     * is ascii or latin1.
     *
     * @param buf A byte buffer to get the bytes from.  Should be ascii or latin1.
     * @param off The offset into buf.
     * @param len The length to get.
     * @return A string.
     */
    public static String bytesToString(ByteBuffer buf, int off, int len) {
        if (buf == null)
            throw new IllegalArgumentException("null byte buffer provided");

        byte[] bbuf = new byte[len];
        buf.position(off);
        buf.get(bbuf);
        char[] cbuf = new char[len];
        for (int i = 0; i < bbuf.length; i++) {
            cbuf[i] = (char) bbuf[i];
        }

        return new String(cbuf);
    }
}

Related

  1. byteBufferToString(ByteBuffer buffer)
  2. byteBufferToString(ByteBuffer buffer)
  3. ByteBufferToString(ByteBuffer buffer, Charset charset)
  4. byteBufferToString(ByteBuffer buffer, String encoding)
  5. byteBufferToString(ByteBuffer stringBuf)
  6. convertBufferToString(ByteBuffer buffer)
  7. decodeString(ByteBuffer bb)
  8. decodeString(ByteBuffer buffer, String charset)
  9. decodeString(ByteBuffer src)