1

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

4
  • What do you wanna know exactly? How to create a BytesMessage? Commented Jun 27, 2012 at 15:18
  • Have you tried String.getBytes(Charset) ? Commented Jun 27, 2012 at 15:18
  • 1
    Well I want to take a String that I already have and convert that into a BytesMessage. I am not too familiar with BytesMessage as I am making changes to already existing code, so is this the wrong way to go about doing this? And yes, I have done that, I can get the String to a bytes[] array but is there a way to convert that into a BytesMessage? Commented Jun 27, 2012 at 15:19
  • If the goal is to encrypt your message, why don't you use the built-in capability of your JMS provider? Commented Jun 27, 2012 at 15:23

3 Answers 3

2
 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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

-1

you can use

byte[] String#getBytes() 

to get a byte array from a string and write it to a ByteMessage

1 Comment

BytesMessage is an interface, not a class. You have to find a factory or an implementation of it in JMS to use it ; though I don't enough know it to give you roasted solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.