将 ByteBuffer 的一部分转换为字符串

发布于 2024-09-04 14:24:45 字数 562 浏览 6 评论 0原文

我有一个 ByteBuffer ,其中包含由 String.getBytes(charsetName),其中“containing”表示字符串包含 ByteBuffer 的 position( )limit()

对我来说,取回绳子的最佳方法是什么? (假设我知道编码字符集)有什么比下面更好的(这看起来有点笨拙)

byte[] ba = new byte[bbuf.remaining()];
bbuf.get(ba);
try {
    String s = new String(ba, charsetName);
}
catch (UnsupportedEncodingException e) {
    /* take appropriate action */
}

I have a ByteBuffer containing bytes that were derived by String.getBytes(charsetName), where "containing" means that the string comprises the entire sequence of bytes between the ByteBuffer's position() and limit().

What's the best way for me to get the string back? (assuming I know the encoding charset) Is there anything better than the following (which seems a little clunky)

byte[] ba = new byte[bbuf.remaining()];
bbuf.get(ba);
try {
    String s = new String(ba, charsetName);
}
catch (UnsupportedEncodingException e) {
    /* take appropriate action */
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不吻晚风 2024-09-11 14:24:45
String s = Charset.forName(charsetName).decode(bbuf).toString();
String s = Charset.forName(charsetName).decode(bbuf).toString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文