【问题标题】:Converting part of a ByteBuffer to a String将 ByteBuffer 的一部分转换为字符串
【发布时间】:2010-06-07 17:59:53
【问题描述】:

我有一个 ByteBuffer,其中包含由 String.getBytes(charsetName) 派生的字节,其中“包含”意味着该字符串包含 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 */
}

【问题讨论】:

    标签: java string nio bytebuffer


    【解决方案1】:
    String s = Charset.forName(charsetName).decode(bbuf).toString();
    

    【讨论】:

    • 哇!太棒了——它“闻起来”好像应该做点什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    相关资源
    最近更新 更多