converting streams to blocks of strings and vice-versa
I have developed a java/scala XMPP client app that sends data asynchronously using (say) a write
method and receives data using a listener
method. The listener
method receives data as discrete XMPP message packets and processes them using a processPacket
method (which I can modify based on what I want to do with the received data)
I want to hook up a 3rd party library that reads data from an inputstream
and writes to an outputstream
. Specifically, I want the inputstream
of the 3rd party library to be emulated using the data received via my listener
method and the outputstream
to be emulated by my write
method.
What would be the easiest way to do this? I know that this requires conversion from a stream to chunks of strings and vice-versa. Some hints would be appreciated.
The XMPP message packet structure is as follows (though this can be开发者_如何学Go changed if needed):
<message to = ... from = ...><body>data</body></message>
Use a ByteArrayInputStream
to create an input stream for a given String. You have to think about encoding, because your sending bytes instead of characters.
String text = message.getBody(); // that's what you need?
InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
For the other way round, you write to an ByteArrayOutputStream
and create a new String from it's bytes:
String text = new String( baos.toByteArray(), "UTF-8" );
Again - don't forget to think about character encoding.
精彩评论