将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;
}
}