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

来源:互联网 发布:凉山新闻网络电视频道 编辑:程序博客网 时间:2024/05/16 08:40
 
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. /**  
  16. * 将bytebuffer转换成string    
  17. * @param str  
  18. */  
  19. public static IoBuffer stringToIoBuffer(String str)   
  20. {   
  21.   
  22.        byte bt[] = str.getBytes();   
  23.   
  24.        IoBuffer ioBuffer = IoBuffer.allocate(bt.length);   
  25.        ioBuffer.put(bt, 0, bt.length);   
  26.        ioBuffer.flip();   
  27.        return ioBuffer;   
  28. }   
  29. /**  
  30. * 将IoBuffer转换成string    
  31. * @param str  
  32. */  
  33. public static IoBuffer byteToIoBuffer(byte [] bt,int length)   
  34. {   
  35.   
  36.        IoBuffer ioBuffer = IoBuffer.allocate(length);   
  37.        ioBuffer.put(bt, 0, length);   
  38.        ioBuffer.flip();   
  39.        return ioBuffer;   
  40. }   
  41. /**  
  42. * 将IoBuffer转换成byte    
  43. * @param str  
  44. */  
  45. public static byte [] ioBufferToByte(Object message)   
  46. {   
  47.       if (!(message instanceof IoBuffer))   
  48.       {   
  49.           return null;   
  50.       }   
  51.       IoBuffer ioBuffer = (IoBuffer)message;   
  52.       byte[] b = new byte[ioBuffer.limit()];   
  53.       ioBuffer.get(b);   
  54.       return b;   
  55. }   
  56. /**  
  57. * 将IoBuffer转换成string    
  58. * @param butBuffer  
  59. */  
  60. public static String ioBufferToString(Object message)   
  61. {   
  62.       if (!(message instanceof IoBuffer))   
  63.       {   
  64.         return "";   
  65.       }   
  66.       IoBuffer ioBuffer = (IoBuffer) message;   
  67.       byte[] b = new byte [ioBuffer.limit()];   
  68.       ioBuffer.get(b);   
  69.       StringBuffer stringBuffer = new StringBuffer();   
  70.   
  71.       for (int i = 0; i < b.length; i++)   
  72.       {   
  73.   
  74.        stringBuffer.append((char) b [i]);   
  75.       }   
  76.        return stringBuffer.toString();   
  77. }  
原创粉丝点击