您的位置:首页 > 编程语言 > Java开发

java过滤非汉字的utf8的字符

2016-06-05 22:01 501 查看
http://outofmemory.cn/code-snippet/2616/java-guolv-negate-hanzi-utf8-charaeterstatic public String filterOffUtf8Mb4(String text) throws UnsupportedEncodingException {
byte[] bytes = text.getBytes("utf-8");
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
int i = 0;
while (i < bytes.length) {
short b = bytes[i];
if (b > 0) {
buffer.put(bytes[i++]);
continue;
}
b += 256;
if ((b ^ 0xC0) >> 4 == 0) {
buffer.put(bytes, i, 2);
i += 2;
}
else if ((b ^ 0xE0) >> 4 == 0) {
buffer.put(bytes, i, 3);
i += 3;
}
else if ((b ^ 0xF0) >> 4 == 0) {
i += 4;
}
}
buffer.flip();
return new String(buffer.array(), "utf-8");
}utf8是变长字符集,单个字符占用1~4个字节。mysql在选择utf8字符集时,最多只能存储3个字节的utf8字符,如果想要保存任意的utf8字符,数据必须用utf8mb4字符集,有些情况下,不能变更已选定的字符集,只好不得以而为之,把输入中的4个字节的utf8字符全部过滤掉,好在,utf8字符集中,汉字是3个字节的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: