Last active
April 10, 2020 18:17
-
-
Save reddikih/00ed63847f9f4e620e9d4772d69cbee5 to your computer and use it in GitHub Desktop.
java convert bytebuffer to string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.ByteBuffer; | |
import java.nio.charset.Charset; | |
... | |
/** | |
Method Usage | |
ByteBuffer bf = string2ByteBuffer("test", Charset.forName("UTF-8")); | |
**/ | |
public static ByteBuffer string2ByteBuffer(String s, Charset charset) { | |
return ByteBuffer.wrap(s.getBytes(charset)); | |
} | |
public static String byteBuffer2String(ByteBuffer buf, Charset charset) { | |
byte[] bytes; | |
if (buf.hasArray()) { | |
bytes = buf.array(); | |
} else { | |
buf.rewind(); | |
bytes = new byte[buf.remaining()]; | |
} | |
return new String(bytes, charset); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment