---
title: "MINA中IoBuffer、byte[]、String之间转换 "
author: "andinker"
date: "2013-11-22T00:11:19Z"
tags: []
categories: ["编程语言"]
slug: "mina-iobuffer-byte-string"
draft: false
lastmod: "2013-11-22T00:11:19Z"
id: 1979097
url: "https://andinker.iteye.com/blog/1979097"
---

Java代码

01. /\**
02. * 将byte\[]转换成string
03. * @param butBuffer
04. \*/
05. public static String byteToString(byte \[] b)
06. {
07. StringBuffer stringBuffer = new StringBuffer();
08. for (int i = 0; i &lt; b.length; i++)
09. {
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 &lt; b.length; i++)
67. {
68. stringBuffer.append((char) b \[i]);
69. }
70. return stringBuffer.toString();
71. }