【问题标题】:Convert ByteMessage to String?将 ByteMessage 转换为字符串?
【发布时间】:2018-05-14 22:11:24
【问题描述】:

ByteMessage 转换为String 的最佳方法是什么?我有下面的代码,我们有更干净的方法吗?

BytesMessage byteMessage; // set byteMessage

byte[] byteArr = new byte[(int)byteMessage.getBodyLength()];

for (int i = 0; i < (int) byteMessage.getBodyLength(); i++) {
    byteArr[i] = byteMessage.readByte();
}
String msg = new String(byteArr);   

【问题讨论】:

  • 显而易见的方式是byteMessage.toString(),还是你想要其他格式?
  • 我只需要正文,不需要标题...

标签: java jms


【解决方案1】:

BytesMessage specification 有一个可能有用的方法 readUTF()。只需调用此方法替换从 BytesMessage 到 String 定义的所有行。

【讨论】:

    【解决方案2】:

    好吧,首先调用 readBytes(byte[]) 可能会更有效。

    其次,您正在使用平台字符编码将字节转换为字符串,这总是很危险的。您应该使用显式字符集。要么是为消息类型指定的已知字符集,要么可能是作为消息属性包含的字符集。

    【讨论】:

      【解决方案3】:

      如果您知道这些字节是 UTF-8 编码的,请使用BytesMessage.readUTF() 便捷方法:

      String s = byteMessage.readUTF();
      

      如果byte[] 数组表示使用不同字符编码的字符串,例如UTF-16,使用String(byte[], java.lang.String)构造函数:

      byte[] byteArr = new byte[(int)byteMessage.getBodyLength()];
      byteMessage.readBytes(byteArr); 
      String msg = new String(byteArr, "UTF-16");  
      

      最后,考虑使用TextMessage 来避免麻烦。

      【讨论】:

        【解决方案4】:

        这可能对你有帮助

         String msg = byteArr.readUTF();
        

        你也可以通过使用来避免循环

         byteMessage.readBytes(byteArr);
        

        【讨论】:

        • 为什么不呢?我会再次检查 javadoc
        • 你说得对,我快速浏览了 javadoc 并没有看到它在谈论 2 个不同的案例。
        猜你喜欢
        • 2019-10-10
        • 2019-01-05
        • 2015-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多