CharsetKit.java 2.4 KB

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