I am trying to convert a String to a JMS BytesMessage. Is there a good way to do this?
I need to do this because I have a method that takes in a String that is decrypted and I need to convert it into a BytesMessage in order to decrypt the message.
Thanks
byte[] bArray = "foo".getBytes("UTF-8");
BytesMessage msg = session.createBytesMessage(); // throws JMSException
msg.writeBytes(bArray);
Of course, like Arcadien said, you need to execute the code in an appropriate environment to obtain the javax.jms.Session object from.
you can use
byte[] String#getBytes()
to get a byte array from a string and write it to a ByteMessage
A bit late, but better late than never.
The @Carlo answer is essentially correct, except that you must catch an exception if you use getBytes
with a String
parameter.
Here is a variation (of the getBytes call) that will not throw an exception:
final byte[] byteArray = "blammy".getBytes(StandardCharsets.UTF_8);
final BytesMessage bytesMessage = session.createBytesMessage();
bytesMessage.writeBytes(byteArray);
The StandardCharsets
class defines charsets that are guaranteed to be available on every implementation of the Java platform.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.