StringUtils.java
2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package cn.com.glsx.stdinterface.modules.util;
import lombok.extern.slf4j.Slf4j;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 项目名:ne-shield-insurancenter
* 包名: cn.com.glsx.insurance.modules.util
* 作者: Yanglinlong
* 日期: 2021/7/6 16:51
*/
@Slf4j
public class StringUtils extends org.apache.commons.lang.StringUtils {
/**
* 按字节长度分割字符串
*
* @param orgin 需要截取的字符串
* @param blength 需要保留的字节长度
* @param charsetName 编码,对于字符集为UTF-8的数据库,请指定编码为UTF-8;字符集为GBK的数据库,请指定编码GBK
* @return 分割后的字符串
* @throws UnsupportedEncodingException 不支持的字符编码
*/
public static List<String> subStringb2(String orgin, int blength, String charsetName) throws UnsupportedEncodingException {
List<String> result = new ArrayList<>();
int length;
byte[] bs = orgin.getBytes(charsetName);
while (bs.length > 0) {
length = blength;
if (length >= bs.length) {
result.add(new String(bs, 0, bs.length, charsetName));
break;
}
if ("UTF8".equals(charsetName.toUpperCase()) || "UTF-8".equals(charsetName.toUpperCase())) {
while (length > 0) {
if ((bs[length] | 0x7F) == 0x7F) {
break;
}
if ((bs[length] & 0xC0) == 0xC0) {
break;
}
length--;
}
} else if ("GBK".equals(charsetName.toUpperCase())) {
boolean removLast = length % 2 == 1;
for (int i = 0; i < length; i++) {
if ((bs[i] | 0x7F) == 0x7F) {
removLast = !removLast;
}
}
if (removLast) {
length--;
}
} else if ("UNICODE".equals(charsetName.toUpperCase())) {
if (length % 2 == 1) {
length--;
}
} else if ("UTF-16".equals(charsetName.toUpperCase()) || "UTF16".equals(charsetName.toUpperCase())) {
if (length % 2 == 1) {
length--;
}
} else if ("UTF-16BE".equals(charsetName.toUpperCase())) {
if (length % 2 == 1) {
length--;
}
} else if ("UTF-16LE".equals(charsetName.toUpperCase())) {
if (length % 2 == 1) {
length--;
}
}
result.add(new String(bs, 0, length, charsetName));
bs = Arrays.copyOfRange(bs, length, bs.length);
}
if (result.size() == 0) {
result.add("");
}
return result;
}
}