1. import java.io.UnsupportedEncodingException; 
  2. import java.nio.ByteBuffer; 
  3. /** 
  4.  *  
  5.  * @author huangyh1 
  6.  * 
  7.  */ 
  8. public class ByteBufferStringOperation {   
  9.    
  10.     public static String ByteBufferToString(ByteBuffer buffer)   
  11.             throws UnsupportedEncodingException {   
  12.    
  13.         buffer.flip();   
  14.         byte[] array = new byte[buffer.limit()];   
  15.         for (int i = 0; i < buffer.limit(); i++) {   
  16.             array[i] = buffer.get();   
  17.         }   
  18.         String content = new String(array, "utf8");   
  19.         array = null;   
  20.         return content;   
  21.    
  22.     }   
  23.    
  24.     public static ByteBuffer StringToByteBuffer(String content, int size)   
  25.             throws UnsupportedEncodingException {   
  26.         if (size <= 0) {   
  27.             System.err.println("invalid size");   
  28.             return null;   
  29.         }   
  30.         ByteBuffer buffer = ByteBuffer.allocate(size);   
  31.         buffer.put(content.getBytes("utf8"));   
  32.         return buffer;   
  33.     }   
  34.    
  35.     public static void main(String[] args) {   
  36.         try {   
  37.             String jj = "helloworld";   
  38.             ByteBuffer buffer = ByteBufferStringOperation.StringToByteBuffer(   
  39.                     jj, 1024 * 256);   
  40.             String fuck;   
  41.             fuck = ByteBufferStringOperation.ByteBufferToString(buffer);   
  42.             System.out.println(fuck);   
  43.         } catch (UnsupportedEncodingException e) {   
  44.             // TODO Auto-generated catch block   
  45.             e.printStackTrace();   
  46.         }   
  47.    
  48.     }   
  49. }