Java: Converting String to and from ByteBuffer and associated problems

前端 未结 3 606
名媛妹妹
名媛妹妹 2020-12-02 06:44

I am using Java NIO for my socket connections, and my protocol is text based, so I need to be able to convert Strings to ByteBuffers before writing them to the SocketChannel

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 07:01

    Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

    1. Reset the encoder via the reset method, unless it has not been used before;
    2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
    3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
    4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

    By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

提交回复
热议问题