Here you can find the source of substringByByteCount(String str, int byteCount)
public static String substringByByteCount(String str, int byteCount)
//package com.java2s; //License from project: Open Source License public class Main { public static String substringByByteCount(String str, int byteCount) { byte[] bytes = str.getBytes(); if (bytes.length <= byteCount) { return str; }//from w w w.j ava 2 s .com int strIndex = 0; for (int i = 0; i < bytes.length;) { int len = utf8Len(bytes[i]); if (i + len <= byteCount) { i += len; strIndex++; } else { break; } } return str.substring(0, strIndex); } public static int utf8Len(byte b) { int num = b & 255; if (num < 0x80) return 1; if (num < 0xe0) return 2; if (num < 0xf0) return 3; if (num < 0xf8) return 4; return 5; } }