java按字节截取字符串
/**
* 截取字符串,按照指定的有效编码格式,指定的字节长度,以及截断方向(右截断/左截断)。
* 返回的字符串的字节长度将小于等于指定长度。可能为空字符串。 * @author leo_soul
* @param original 原字符串
* @param charsetName 编码格式名
* @param byteLen 字节长度
* @param isRightTruncation 是否右截断。
* @return
* @throws UnsupportedEncodingException
*/
protected String sbjTrim(String original,int byteLen ) throws UnsupportedEncodingException{
String charsetName="utf-8";
boolean isRightTruncation=true;
if(original==null || "".equals(original.trim()))return "";
if(charsetName==null || "".equals(charsetName))throw new UnsupportedEncodingException("subStrByByteLen方法,必须指定编码格式");
byte[] bytes = original.getBytes(charsetName); if(byteLen<=0)return "";
if(byteLen>=bytes.length)return original;
int tempLen = 0;
String result = "";
if(isRightTruncation){ //右截断
//按照指定字节长度截断,再转成临时String,计算长度。 tempLen = new String(bytes,0,byteLen,charsetName).length();
//根据该长度右截取原字符串。
result = original.substring(0, tempLen);
//超过预订字节长度,则减一个字符截取。
if(result!=null && !"".equals(result.trim()) && result.getBytes(charsetName).length>byteLen){ //判断字节长度。
result = original.substring(0,tempLen-1); //超长,去掉一个字符
}
}else{ //左截断
//全字符长-左截预订点(注意必须是预定点,bytes.length-byteLen+1)所右截断的串的字符长+1,计算长度。(为了给左截串多留一个字符。)
//tempLen = original.length()-new String(bytes,0,bytes.length-byteLen+1,charsetName).length()+1;
//根据该长度左截取原字符串。注意起始下标计算方法。
//result = original.substring(original.length()-tempLen);
//由于以上公式可以展开,由此得到简化版。
tempLen = new String(bytes,0,bytes.length-byteLen+1,charsetName).length()-1;
result = original.substring(tempLen);
if(result!=null && !"".equals(result.trim()) && result.getBytes(charsetName).length>byteLen){ //判断字节长度。
result = original.substring(tempLen+1); //超长,去掉一个符(左截) 字
}
}
result+="...";
return result;
}