java过滤非汉字的utf8的字符

 将hive中的数据保存在mysql数据库,

title为字符串,保存过程中报错如下:

java.sql.SQLException: Incorrect string value: '\xF4\x80\xB3\x8A \xE6...' for column 'title' at row 1

该异常说明:在hive中title字段中存在不是utf8的字符串,用了好多办法,将title字符串转换为二进制进行保存,

但是看起来很不爽,于是找到了一个好办法,将所有非utf8的全部过滤掉,成功插入。

package com.scala.utils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;


public class stringUtil {
    public static void main(String[] args) {
        String str = "本报讯(记者 张志鹏)为深化庆祝改革开放40年群众性主题宣传教育活动,省委宣传部组织开展“将改革开放进行到底”百姓宣讲活动全省巡回宣讲。";
        String binary = toBinary(str);
        System.out.println(binary);
        System.out.println(toString(binary));

    }
    //字符串转成字符数组
    public static String toBinary(String str){
        //把字符串转成字符数组
        char[] strChar=str.toCharArray();
        String result="";
        for(int i=0;i<strChar.length;i++){
            //toBinaryString(int i)返回变量的二进制表示的字符串
            //toHexString(int i) 八进制
            //toOctalString(int i) 十六进制
            result +=Integer.toBinaryString(strChar[i])+" ";
        }
        return result;
    }
    //将二进制转换成字符

    public static String toString(String binary) {
        String[] tempStr=binary.split(" ");
        char[] tempChar=new char[tempStr.length];
        for(int i=0;i<tempStr.length;i++) {
            tempChar[i]=BinstrToChar(tempStr[i]);
        }
        return String.valueOf(tempChar);
    }
  
    //java过滤非汉字的utf8的字符
    public static String filterOffUtf8Mb4(String text) {
        byte[] bytes= "".getBytes();
        try{
            bytes = text.getBytes("utf-8");

        }catch (Exception e){

        }
        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 >> 5) ^ 0x6) == 0) {
                buffer.put(bytes, i, 2);
                i += 2;
            } else if (((b >> 4) ^ 0xE) == 0) {
                buffer.put(bytes, i, 3);
                i += 3;
            } else if (((b >> 3) ^ 0x1E) == 0) {
                i += 4;
            } else if (((b >> 2) ^ 0x3E) == 0) {
                i += 5;
            } else if (((b >> 1) ^ 0x7E) == 0) {
                i += 6;
            } else {
                buffer.put(bytes[i++]);
            }
        }
        buffer.flip();
        String str="";
        try{
            str = new String(buffer.array(), "utf-8");

        }catch (Exception e){

        }
        return str;
    }
   


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值