Here you can find the source of truncateByByteLength(String string, int maxBytes, Charset charset)
public static String truncateByByteLength(String string, int maxBytes, Charset charset)
//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 }