Search

Monday, June 8, 2015

How to convert ByteBuffer to String in Java

You can easily convert ByteBuffer to String  in Java if you know how to convert byte array to String. Why? because its very easy to convert ByteBuffer to byte array and vice versa. All you need to do is call the ByteBuffer.array() method, it will return you the byte array used by java.nio.ByteBuffer class, later you can easily create String from that byte array. Though always remember to provide correct character encoding while converting byte array to String. For example, if you know that ByteBuffer is filled with bytes encoded in UTF-8 then you must use same encoding while creating String from that byte array. String class provides an overloaded constructor which accepts character encoding along with byte array.  You can the snippet shared in this example to do the job. ByteBuffer is one of the very useful class in java.nio package which is used to read data from channels and write data into channel directly. Same ByteBuffer can be used to read and write data. If you want to read from ByteBuffer just call the flip() method and it will convert ByteBuffer into reading mode. In this article, you will learn how to convert ByteBuffer to String in Java. I have a given a simple example, but if you still any doubt you can always leave a comment or question.
Read more »

No comments:

Post a Comment