CharsetKit.java 2.3 KB

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