- import java.io.UnsupportedEncodingException;
- import java.nio.ByteBuffer;
- /**
- *
- * @author huangyh1
- *
- */
- public class ByteBufferStringOperation {
- public static String ByteBufferToString(ByteBuffer buffer)
- throws UnsupportedEncodingException {
- buffer.flip();
- byte[] array = new byte[buffer.limit()];
- for (int i = 0; i < buffer.limit(); i++) {
- array[i] = buffer.get();
- }
- String content = new String(array, "utf8");
- array = null;
- return content;
- }
- public static ByteBuffer StringToByteBuffer(String content, int size)
- throws UnsupportedEncodingException {
- if (size <= 0) {
- System.err.println("invalid size");
- return null;
- }
- ByteBuffer buffer = ByteBuffer.allocate(size);
- buffer.put(content.getBytes("utf8"));
- return buffer;
- }
- public static void main(String[] args) {
- try {
- String jj = "helloworld";
- ByteBuffer buffer = ByteBufferStringOperation.StringToByteBuffer(
- jj, 1024 * 256);
- String fuck;
- fuck = ByteBufferStringOperation.ByteBufferToString(buffer);
- System.out.println(fuck);
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
转载于:https://blog.51cto.com/steveskylook/755435