import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
@Slf4j
public class CodeUtil {
public static String filterOffUtf8Mb4(String text) throws UnsupportedEncodingException {
if (StringUtils.isEmpty(text)) {
return text;
}
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;
}else{
i+=1;
}
}
buffer.flip();
String delStr = new String(buffer.array(), "utf-8");
if (text.equals(delStr)) {
return text;
}
byte[] delBytes = delStr.getBytes("UTF-8");
int j = 0;
int n = 0;
ByteBuffer buffer2 = ByteBuffer.allocate(bytes.length);
while (j < bytes.length) {
if (bytes[j] != delBytes[j - n]) {
bytes[j] = 63;
n++;
}
buffer2.put(bytes[j++]);
}
buffer2.flip();
String str = new String(buffer2.array(), "utf-8");
return str;
}
public static String decode(String str) {
byte[] bt = null;
String decodeStr = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
decodeStr = new String(new String(bt, "GBK").getBytes(), "utf-8");
} catch (IOException e) {
log.error("解码失败");
e.printStackTrace();
return "解码失败";
}
return decodeStr;
}
}