StringSerializer.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. package com.sdyc.ndmp.protobuf.serializer;
  2. import java.nio.charset.Charset;
  3. /**
  4. * <pre>
  5. *
  6. * Created by IntelliJ IDEA.
  7. * User: ZhenQin
  8. * Date: 13-10-8
  9. * Time: 上午9:57
  10. * To change this template use File | Settings | File Templates.
  11. *
  12. * </pre>
  13. *
  14. * @author ZhenQin
  15. */
  16. public class StringSerializer implements Serializer<String> {
  17. private static final long serialVersionUID = 1L;
  18. /**
  19. * 默认支持的编码类型
  20. */
  21. private Charset charset = Charset.forName("UTF-8");
  22. /**
  23. * 默认是UTF-8的数据编码类型
  24. */
  25. public StringSerializer() {
  26. }
  27. /**
  28. * 自己指定数据编码类型
  29. * @param charset
  30. */
  31. public StringSerializer(Charset charset) {
  32. this.charset = charset;
  33. }
  34. /**
  35. * 自己指定数据编码类型
  36. * @param charset
  37. */
  38. public StringSerializer(String charset) {
  39. this.charset = Charset.forName(charset);
  40. }
  41. /**
  42. * Serialize the given object to binary data.
  43. *
  44. * @param s object to serialize
  45. * @return the equivalent binary data
  46. */
  47. @Override
  48. public byte[] serialize(String s) {
  49. return s.getBytes(charset);
  50. }
  51. public String deserialize(byte[] bytes, int offset, int length) {
  52. return new String(bytes, offset, length, charset);
  53. }
  54. /**
  55. * Deserialize an object from the given binary data.
  56. *
  57. * @param bytes object binary representation
  58. * @return the equivalent object instance
  59. */
  60. @Override
  61. public String deserialize(byte[] bytes) {
  62. return new String(bytes, charset);
  63. }
  64. public Charset getCharset() {
  65. return charset;
  66. }
  67. public void setCharset(Charset charset) {
  68. this.charset = charset;
  69. }
  70. /**
  71. * 把非字符串化的字符串转换成 String
  72. * @param bytes
  73. * @return
  74. */
  75. public static String toString(byte[] bytes) {
  76. StringBuffer strBuf = new StringBuffer();
  77. for (int i = 0; i < bytes.length; i++) {
  78. strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
  79. strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
  80. }
  81. return strBuf.toString();
  82. }
  83. /**
  84. * 把非字符串化的字符串转换成 byte
  85. * @param str
  86. * @return
  87. */
  88. public static byte[] toBytes(String str) {
  89. byte[] bytes = new byte[str.length() / 2];
  90. for (int i = 0; i < str.length(); i += 2) {
  91. char c = str.charAt(i);
  92. bytes[i / 2] = (byte) ((c - 'a') << 4);
  93. c = str.charAt(i + 1);
  94. bytes[i / 2] += (c - 'a');
  95. }
  96. return bytes;
  97. }
  98. }