【问题标题】:Can we convert a byte array into an InputStream in Java?我们可以在 Java 中将字节数组转换为 InputStream 吗?
【发布时间】:2010-12-20 14:27:15
【问题描述】:

我们可以在 Java 中将字节数组转换为 InputStream 吗?我一直在网上找,但没找到。

我有一个以 InputStream 作为参数的方法。

我拥有的 InputStream cph 是 base64 编码的,所以我必须使用它来解码它

BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(cph);

现在如何将decodedBytes 再次转换为InputStream

【问题讨论】:

  • API 文档页面顶部的“使用”链接对于这类问题非常有用。

标签: java base64 inputstream


【解决方案1】:

使用ByteArrayInputStream:

InputStream is = new ByteArrayInputStream(decodedBytes);

【讨论】:

    【解决方案2】:

    如果你使用Robert Harder's Base64 utility,那么你可以这样做:

    InputStream is = new Base64.InputStream(cph);
    

    或者使用 sun 的 JRE,你可以这样做:

    InputStream is = new
    com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)
    

    但是,不要依赖该类继续成为 JRE 的一部分,或者甚至继续做它今天似乎在做的事情。 Sun 说不要使用它。

    还有其他关于Base64解码的Stack Overflow问题,如this one.

    【讨论】:

    • 不要使用 sun 类,它是私有的,不应该使用,因为它可以随时更改。
    • 我将编辑我的答案以包含可怕的警告。问题中的代码已经在使用BASE64Decoder,大概是sun.misc.BASE64Decoder
    猜你喜欢
    • 2010-11-18
    • 2016-04-15
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2011-01-10
    相关资源
    最近更新 更多