将流转换为字符串块,反之亦然

发布于 2024-10-18 01:39:59 字数 553 浏览 2 评论 0原文

我开发了一个 java/scala XMPP 客户端应用程序,它使用(例如)写入方法异步发送数据,并使用侦听器方法接收数据。 listener 方法接收作为离散 XMPP 消息包的数据,并使用 processPacket 方法处理它们(我可以根据我想要对接收到的数据执行的操作进行修改)

我想要连接从输入流读取数据并将数据写入输出流的第 3 方库。具体来说,我希望使用通过我的 listener 方法接收到的数据来模拟第 3 方库的 inputstream ,并通过以下方式模拟 outputstream我的 write 方法。

做到这一点最简单的方法是什么?我知道这需要从流转换为字符串块,反之亦然。一些提示将不胜感激。

XMPP消息包结构如下(尽管可以根据需要更改):

<message to = ... from = ...><body>data</body></message>

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 changed if needed):

<message to = ... from = ...><body>data</body></message>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

朱染 2024-10-25 01:39:59

使用 ByteArrayInputStream 为给定的字符串创建输入流。您必须考虑编码,因为您发送的是字节而不是字符。

String text = message.getBody();  // that's what you need?
InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));

相反,您可以写入 ByteArrayOutputStream 并从其字节创建一个新字符串:

String text = new String( baos.toByteArray(), "UTF-8" );

同样,不要忘记考虑字符编码。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文