提交 | 用户 | 时间
|
e57a89
|
1 |
package com.jcdm.common.core.text; |
懒 |
2 |
|
|
3 |
import java.nio.charset.Charset; |
|
4 |
import java.nio.charset.StandardCharsets; |
|
5 |
import com.jcdm.common.utils.StringUtils; |
|
6 |
|
|
7 |
/** |
|
8 |
* 字符集工具类 |
|
9 |
* |
|
10 |
* @author jc |
|
11 |
*/ |
|
12 |
public class CharsetKit |
|
13 |
{ |
|
14 |
/** ISO-8859-1 */ |
|
15 |
public static final String ISO_8859_1 = "ISO-8859-1"; |
|
16 |
/** UTF-8 */ |
|
17 |
public static final String UTF_8 = "UTF-8"; |
|
18 |
/** GBK */ |
|
19 |
public static final String GBK = "GBK"; |
|
20 |
|
|
21 |
/** ISO-8859-1 */ |
|
22 |
public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1); |
|
23 |
/** UTF-8 */ |
|
24 |
public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8); |
|
25 |
/** GBK */ |
|
26 |
public static final Charset CHARSET_GBK = Charset.forName(GBK); |
|
27 |
|
|
28 |
/** |
|
29 |
* 转换为Charset对象 |
|
30 |
* |
|
31 |
* @param charset 字符集,为空则返回默认字符集 |
|
32 |
* @return Charset |
|
33 |
*/ |
|
34 |
public static Charset charset(String charset) |
|
35 |
{ |
|
36 |
return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset); |
|
37 |
} |
|
38 |
|
|
39 |
/** |
|
40 |
* 转换字符串的字符集编码 |
|
41 |
* |
|
42 |
* @param source 字符串 |
|
43 |
* @param srcCharset 源字符集,默认ISO-8859-1 |
|
44 |
* @param destCharset 目标字符集,默认UTF-8 |
|
45 |
* @return 转换后的字符集 |
|
46 |
*/ |
|
47 |
public static String convert(String source, String srcCharset, String destCharset) |
|
48 |
{ |
|
49 |
return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); |
|
50 |
} |
|
51 |
|
|
52 |
/** |
|
53 |
* 转换字符串的字符集编码 |
|
54 |
* |
|
55 |
* @param source 字符串 |
|
56 |
* @param srcCharset 源字符集,默认ISO-8859-1 |
|
57 |
* @param destCharset 目标字符集,默认UTF-8 |
|
58 |
* @return 转换后的字符集 |
|
59 |
*/ |
|
60 |
public static String convert(String source, Charset srcCharset, Charset destCharset) |
|
61 |
{ |
|
62 |
if (null == srcCharset) |
|
63 |
{ |
|
64 |
srcCharset = StandardCharsets.ISO_8859_1; |
|
65 |
} |
|
66 |
|
|
67 |
if (null == destCharset) |
|
68 |
{ |
|
69 |
destCharset = StandardCharsets.UTF_8; |
|
70 |
} |
|
71 |
|
|
72 |
if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) |
|
73 |
{ |
|
74 |
return source; |
|
75 |
} |
|
76 |
return new String(source.getBytes(srcCharset), destCharset); |
|
77 |
} |
|
78 |
|
|
79 |
/** |
|
80 |
* @return 系统字符集编码 |
|
81 |
*/ |
|
82 |
public static String systemCharset() |
|
83 |
{ |
|
84 |
return Charset.defaultCharset().name(); |
|
85 |
} |
|
86 |
} |