Java ByteBuffer to String

后端 未结 10 1609
一生所求
一生所求 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条回答
  •  旧时难觅i
    2020-12-07 22:04

    the root of this question is how to decode bytes to string?

    this can be done with the JAVA NIO CharSet:

    public final CharBuffer decode(ByteBuffer bb)

    FileChannel channel = FileChannel.open(
      Paths.get("files/text-latin1.txt", StandardOpenOption.READ);
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    channel.read(buffer);
    
    CharSet latin1 = StandardCharsets.ISO_8859_1;
    CharBuffer latin1Buffer = latin1.decode(buffer);
    
    String result = new String(latin1Buffer.array());
    
    • First we create a channel and read it in a buffer
    • Then decode method decodes a Latin1 buffer to a char buffer
    • We can then put the result, for instance, in a String

提交回复
热议问题