Java ByteBuffer to String

后端 未结 10 1593
一生所求
一生所求 2020-12-07 21:30

Is this a correct approach to convert ByteBuffer to String in this way,

String k = \"abcd\";
ByteBuffer b = ByteBuffer.wrap(k.getBytes());
String v = new Str         


        
10条回答
  •  暖寄归人
    2020-12-07 22:18

    Here is a simple function for converting a byte buffer to string:

    public String byteBufferToString(ByteBuffer bufferData) {
        byte[] buffer = new byte[bufferData.readableByteCount()];
        // read bufferData and insert into buffer 
        data.read(buffer);
        // CharsetUtil supports UTF_16, ASCII, and many more
        String text = new String(buffer, CharsetUtil.UTF_8);
        System.out.println("Text: "+text);
        return text;
    }
    

提交回复
热议问题