Java - InputStream to Reader

Java –リーダーへの入力ストリーム

このクイックチュートリアルでは、Java、Guava、最後にApache Commons IOを使用したconverting an InputStream to a Readerを見ていきます。

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

1. Javaで

まず、すぐに利用できるInputStreamReaderを使用した単純なJavaソリューションを見てみましょう。

@Test
public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect()
  throws IOException {
    InputStream initialStream = new ByteArrayInputStream("With Java".getBytes());

    Reader targetReader = new InputStreamReader(initialStream);

    targetReader.close();
}

2. グアバと

次に–中間バイト配列と文字列を使用してthe Guava solutionを見てみましょう:

@Test
public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect()
  throws IOException {
    InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream();

    byte[] buffer = ByteStreams.toByteArray(initialStream);
    Reader targetReader = CharSource.wrap(new String(buffer)).openStream();

    targetReader.close();
}

Javaソリューションは、このアプローチよりも簡単であることに注意してください。

3. コモンズIO

最後に– Apache Commons IOを使用するソリューション–中間文字列を使用する:

@Test
public void givenUsingCommonsIO_whenConvertingInputStreamIntoReader_thenCorrect()
  throws IOException {
    InputStream initialStream = IOUtils.toInputStream("With Commons IO");

    byte[] buffer = IOUtils.toByteArray(initialStream);
    Reader targetReader = new CharSequenceReader(new String(buffer));

    targetReader.close();
}

これで、入力ストリームをJavaReaderに変換する3つの簡単な方法ができました。