Java Byte Array to String by Charset truncateByByteLength(String string, int maxBytes, Charset charset)

Here you can find the source of truncateByByteLength(String string, int maxBytes, Charset charset)

Description

truncate By Byte Length

License

Open Source License

Declaration

public static String truncateByByteLength(String string, int maxBytes, Charset charset) 

Method Source Code

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

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;

public class Main {
    public static String truncateByByteLength(String string, int maxBytes, Charset charset) {
        CharsetEncoder ce = charset.newEncoder();
        if (string.length() * ce.maxBytesPerChar() <= maxBytes)
            return string;

        CharBuffer chars = CharBuffer.wrap(string);
        ByteBuffer bytes = ByteBuffer.allocate(maxBytes);
        CoderResult result = ce.encode(chars, bytes, true);
        return result.isOverflow() ? new String(bytes.array(), 0, bytes.position(), charset) : string;
    }//  w w  w  . j av  a2  s. c  o  m
}

Related

  1. toString(byte[] bytes, Charset charset)
  2. toString(byte[] bytes, String charsetName)
  3. toString(byte[] data, int from, int length, Charset charset)
  4. toString(final byte[] bytes, final String charsetName)
  5. toUnicode(byte[] isoStr, String charset)
  6. yaml2List(Charset charset, byte[] data)