Java Byte Array to InputStream – 将Java 字节数组转为InputStream

最后修改: 2014年 6月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial we’re going to illustrate how to convert a simple byte[] to an InputStream, first using plain java and then the Guava library.

在这个快速教程中,我们将说明如何将一个简单的byte[]转换为InputStream,首先使用普通java,然后使用Guava库。

This article is part of the “Java – Back to Basic” series here on Baeldung.

本文是“Java – 回到基础“系列的一部分,在Baeldung这里。

2. Convert Using Java

2.使用Java进行转换

First – let’s look at the Java solution:

首先–让我们看看Java的解决方案

@Test
public void givenUsingPlainJava_whenConvertingByteArrayToInputStream_thenCorrect() 
  throws IOException {
    byte[] initialArray = { 0, 1, 2 };
    InputStream targetStream = new ByteArrayInputStream(initialArray);
}

3. Convert Using Guava

3.使用Guava进行转换

Next – let’s use wrap the byte array into the Guava ByteSource – which then allows us to get the stream:

接下来–让我们把字节数组包进Guava的ByteSource–这样我们就可以获得流

@Test
public void givenUsingGuava_whenConvertingByteArrayToInputStream_thenCorrect() 
  throws IOException {
    byte[] initialArray = { 0, 1, 2 };
    InputStream targetStream = ByteSource.wrap(initialArray).openStream();
}

And there you have it – a simple way of opening an InputStream from a byte array.

你已经有了 – 一个从字节数组打开InputStream的简单方法。