java 将 ByteMessage 转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11002772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:22:15  来源:igfitidea点击:

Convert ByteMessage to String?

javajms

提问by user595234

What is best way to convert ByteMessageto String? I have the following code, do we have a more clean way?

什么是转换最好的方式ByteMessageString?我有以下代码,我们有更干净的方法吗?

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);   

回答by rlinden

The BytesMessage specificationhas a method readUTF() that might be helpful. Just replace all lines from BytesMessage up to the definition of the String with a call to this method.

BytesMessage规范有可能会有所帮助的方法的readUTF()。只需调用此方法替换从 BytesMessage 到 String 定义的所有行。

回答by jtahlborn

well, first it would probably be more efficient to call readBytes(byte[]).

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

second, you are converting the bytes to a String using the platform character encoding, which is always dangerous. you should be using an explicit charset. either one known to be specified for the message type, or possibly a charset included as a message property.

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

回答by tgoossens

This might help you out

这可能会帮助你

 String msg = byteArr.readUTF();

You can also avoid the loop by using

您还可以通过使用避免循环

 byteMessage.readBytes(byteArr);

回答by Tomasz Nurkiewicz

If you know that these bytes are UTF-8 encoded, use BytesMessage.readUTF()convenience method:

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

String s = byteMessage.readUTF();

If the byte[]array represents a string encoded with a different character encoding, e.g. UTF-16, use String(byte[], java.lang.String)constructor:

如果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");  

Finally, consider using TextMessageto avoid the whole hustle.

最后,考虑使用TextMessage以避免整个喧嚣。