将ByteArrayInputStream的内容转换为字符串 [英] Convert Contents Of A ByteArrayInputStream To String

查看:133
本文介绍了将ByteArrayInputStream的内容转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了这篇文章,但我没有关注。我已经看到,但是还没有看到使用 ByteArrayOutputStream ByteArrayInputStream 转换为 String 的正确示例。 c $ c>。

I read this post but I am not following. I have seen this but have not seen a proper example of converting a ByteArrayInputStream to String using a ByteArrayOutputStream.

String <的形式检索 ByteArrayInputStream 的内容/ code>,使用的是推荐的 ByteArrayOutputstream 还是有更好的方法?

To retrieve the contents of a ByteArrayInputStream as a String, is using a ByteArrayOutputstream recommended or is there a more preferable way?

考虑此示例并扩展 ByteArrayInputStream 并使用装饰器来增加运行时的功能。是否有兴趣使用 ByteArrayOutputStream 更好的解决方案?

I was considering this example and extend ByteArrayInputStream and utilize a Decorator to increase functionality at run time. Any interest in this being a better solution to employing a ByteArrayOutputStream?

推荐答案

一个 ByteArrayOutputStream 可以从任何 InputStream 中读取,最后产生一个 byte []

A ByteArrayOutputStream can read from any InputStream and at the end yield a byte[].

但是使用 ByteArrayInputStream 则更简单:

int n = in.available();
byte[] bytes = new byte[n];
in.read(bytes, 0, n);
String s = new String(bytes, StandardCharsets.UTF_8); // Or any encoding.

对于 ByteArrayInputStream available()产生字节总数。

评论答案:使用ByteArrayOutputStream

Answer to comment: using ByteArrayOutputStream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
for (;;) {
    int nread = in.read(buf, 0, buf.length);
    if (nread <= 0) {
        break;
    }
    baos.write(buf, 0, nread);
}
in.close();
baos.close();
byte[] bytes = baos.toByteArray();

此处可能是任何InputStream。

Here in may be any InputStream.

这篇关于将ByteArrayInputStream的内容转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆