f14890d74175a6bb575587453f5379d80cb29bd7.svn-base 2.1 KB

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