バイト配列へのJava InputStream

Java InputStream to Byte ArrayおよびByteBuffer

1. 概要

このクイックチュートリアルでは、InputStreambyte[]ByteBufferに変換する方法を見ていきます。最初にプレーンJavaを使用し、次にGuavaとCommonsIOを使用します。

この記事は、例としてここのthe “Java – Back to Basic” seriesの一部です。

参考文献:

SpringのStreamUtilsの概要

SpringのStreamUtilsクラスをご覧ください。

Javaシリアル化の概要

Javaでオブジェクトをシリアライズおよびデシリアライズする方法を学びます。

Java文字列変換

JavaでStringオブジェクトをさまざまなデータ型に変換することに焦点を当てた、迅速で実用的な例。

2. バイト配列に変換

単純な入力ストリームからバイト配列を取得する方法を見てみましょうバイト配列の重要な側面はit enables an indexed (fast) access to each 8-bit (a byte) value stored in memoryです。 したがって、これらのバイトを操作して各ビットを制御できます。 単純な入力ストリームをbyte[]に変換する方法を見ていきます。最初にプレーンJavaを使用し、次にGuavaApache Commons IOを使用します。

2.1. プレーンJavaを使用して変換する

固定サイズのストリームの処理に焦点を当てたJavaソリューションから始めましょう。

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

    byte[] targetArray = new byte[initialStream.available()];
    initialStream.read(targetArray);
}

バッファリングされたストリームの場合-バッファリングされたストリームを処理していて、基になるデータの正確なサイズがわからない場合は、実装をより柔軟にする必要があります。

@Test
public void
  givenUsingPlainJavaOnUnknownSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect()
  throws IOException {
    InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); // not really unknown

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] data = new byte[1024];
    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();
    byte[] byteArray = buffer.toByteArray();
}

2.2. グアバを使用して変換

次に、便利なByteStreamsユーティリティクラスを使用した、単純なGuavaベースのソリューションを見てみましょう。

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

    byte[] targetArray = ByteStreams.toByteArray(initialStream);
}

2.3. CommonsIOを使用して変換する

最後に、Apache Commons IOを使用した簡単なソリューション:

@Test
public void givenUsingCommonsIO_whenConvertingAnInputStreamToAByteArray_thenCorrect()
  throws IOException {
    ByteArrayInputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });

    byte[] targetArray = IOUtils.toByteArray(initialStream);
}

メソッドIOUtils.toByteArray()は入力を内部的にバッファリングするため、バッファリングが必要な場合はno need to use a BufferedInputStream instanceがあります。

3. ByteBufferに変換

それでは、InputStream.からByteBufferを取得する方法を見てみましょう。これはuseful whenever we need to do fast and direct low-level I/O operations in memoryです。

上記のセクションと同じアプローチを使用して、InputStreamByteBufferに変換する方法を見ていきます。最初にプレーンJavaを使用し、次にGuavaとCommonsIOを使用します。

3.1. プレーンJavaを使用して変換する

バイトストリームの場合–基になるデータの正確なサイズを知っています。 ByteArrayInputStream#available メソッドを使用して、バイトストリームをByteBufferに読み込みます。

@Test
public void givenUsingCoreClasses_whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch()
  throws IOException {
    byte[] input = new byte[] { 0, 1, 2 };
    InputStream initialStream = new ByteArrayInputStream(input);
    ByteBuffer byteBuffer = ByteBuffer.allocate(3);
    while (initialStream.available() > 0) {
        byteBuffer.put((byte) initialStream.read());
    }

    assertEquals(byteBuffer.position(), input.length);
}

3.2. グアバを使用して変換

次に、便利なByteStreamsユーティリティクラスを使用した、単純なGuavaベースのソリューションを見てみましょう。

@Test
public void givenUsingGuava__whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch()
  throws IOException {
    InputStream initialStream = ByteSource
      .wrap(new byte[] { 0, 1, 2 })
      .openStream();
    byte[] targetArray = ByteStreams.toByteArray(initialStream);
    ByteBuffer bufferByte = ByteBuffer.wrap(targetArray);
    while (bufferByte.hasRemaining()) {
        bufferByte.get();
    }

    assertEquals(bufferByte.position(), targetArray.length);
}

ここでは、メソッドhasRemaining でwhileループを使用して、すべてのバイトをByteBuffer.に読み込む別の方法を示します。そうしないと、ByteBufferのインデックス位置がゼロになるため、アサーションは失敗します。

3.3. CommonsIOを使用して変換する

そして最後に– Apache Commons IOとIOUtilsクラスを使用します。

@Test
public void givenUsingCommonsIo_whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch()
  throws IOException {
    byte[] input = new byte[] { 0, 1, 2 };
    InputStream initialStream = new ByteArrayInputStream(input);
    ByteBuffer byteBuffer = ByteBuffer.allocate(3);
    ReadableByteChannel channel = newChannel(initialStream);
    IOUtils.readFully(channel, byteBuffer);

    assertEquals(byteBuffer.position(), input.length);
}

4. 結論

この記事では、プレーンJava、Guava、Apache Commons IOを使用して、生の入力ストリームをバイト配列とByteBufferに変換するさまざまな方法について説明しました。

これらすべての例の実装は、GitHub projectにあります。