ITeye博客

MINA中IoBuffer、byte[]、String之间转换

andinker · 2013-11-22 00:11 · mina · 编程语言 · Markdown

Java代码

  1. /**
  2. * 将byte[]转换成string
  3. * @param butBuffer
  4. */
  5. public static String byteToString(byte [] b)
  6. {
  7. StringBuffer stringBuffer = new StringBuffer();
  8. for (int i = 0; i < b.length; i++)
  9. {
  10. stringBuffer.append((char) b [i]);
  11. }
  12. return stringBuffer.toString();
  13. }
  14. /**
  15. * 将bytebuffer转换成string
  16. * @param str
  17. */
  18. public static IoBuffer stringToIoBuffer(String str)
  19. {
  20. byte bt[] = str.getBytes();
  21. IoBuffer ioBuffer = IoBuffer.allocate(bt.length);
  22. ioBuffer.put(bt, 0, bt.length);
  23. ioBuffer.flip();
  24. return ioBuffer;
  25. }
  26. /**
  27. * 将IoBuffer转换成string
  28. * @param str
  29. */
  30. public static IoBuffer byteToIoBuffer(byte [] bt,int length)
  31. {
  32. IoBuffer ioBuffer = IoBuffer.allocate(length);
  33. ioBuffer.put(bt, 0, length);
  34. ioBuffer.flip();
  35. return ioBuffer;
  36. }
  37. /**
  38. * 将IoBuffer转换成byte
  39. * @param str
  40. */
  41. public static byte [] ioBufferToByte(Object message)
  42. {
  43. if (!(message instanceof IoBuffer))
  44. {
  45. return null;
  46. }
  47. IoBuffer ioBuffer = (IoBuffer)message;
  48. byte[] b = new byte[ioBuffer.limit()];
  49. ioBuffer.get(b);
  50. return b;
  51. }
  52. /**
  53. * 将IoBuffer转换成string
  54. * @param butBuffer
  55. */
  56. public static String ioBufferToString(Object message)
  57. {
  58. if (!(message instanceof IoBuffer))
  59. {
  60. return "";
  61. }
  62. IoBuffer ioBuffer = (IoBuffer) message;
  63. byte[] b = new byte [ioBuffer.limit()];
  64. ioBuffer.get(b);
  65. StringBuffer stringBuffer = new StringBuffer();
  66. for (int i = 0; i < b.length; i++)
  67. {
  68. stringBuffer.append((char) b [i]);
  69. }
  70. return stringBuffer.toString();
  71. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。