Java ByteBuffer to String decodeString(ByteBuffer buffer, String charset)

Here you can find the source of decodeString(ByteBuffer buffer, String charset)

Description

Convert the bytes in a given buffer to a string, using a given charset.

License

Open Source License

Parameter

Parameter Description
buffer array of bytes encoded using the given charset
charset name of valid and supported character set

Exception

Parameter Description
RuntimeException if the charset is not supported

Return

string representation of the buffer

Declaration

static String decodeString(ByteBuffer buffer, String charset) 

Method Source Code

//package com.java2s;
/**// www . j  a  v a  2  s.  c  om
 * Copyright (C) 2009-2013 FoundationDB, LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.UnsupportedEncodingException;

import java.nio.ByteBuffer;

public class Main {
    /**
     * Convert the bytes in a given buffer to a string, using a given charset.
     * @param buffer array of bytes encoded using the given charset
     * @param charset name of valid and supported character set
     * @return string representation of the buffer
     * @throws RuntimeException if the charset is not supported
     */
    static String decodeString(ByteBuffer buffer, String charset) {
        if (buffer == null) {
            return null;
        }
        if (charset == null) {
            throw new IllegalArgumentException("charset");
        }
        // Note: String(.., Charset) has *very* different behavior than String(.., "charset")
        // Think carefully, and read the String docs, before changing.
        try {
            return new String(buffer.array(), buffer.position(),
                    buffer.limit() - buffer.position(), charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. byteBufferToString(ByteBuffer buffer, String encoding)
  2. byteBufferToString(ByteBuffer stringBuf)
  3. bytesToString(ByteBuffer buf, int off, int len)
  4. convertBufferToString(ByteBuffer buffer)
  5. decodeString(ByteBuffer bb)
  6. decodeString(ByteBuffer src)
  7. getStr(ByteBuffer buff)
  8. getString(@Nonnull final ByteBuffer src)
  9. getString(ByteBuffer bb)