このクイックチュートリアルでは、 Java、次にGuava、最後にApacheCommonsIOを使用してInputStreamをReaderに変換する方法を見ていきます。

この記事は、ここBaeldungの「Java –BacktoBasic」シリーズの一部です。

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. グアバと

次に–中間バイト配列と文字列を使用してGuavaソリューションを見てみましょう。

@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. CommonsIOを使用

最後に、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();
}

これで、入力ストリームをJava Readerに変換する3つの簡単な方法がわかりました。 GitHubでサンプルを確認してください。