Java – InputStream to Reader
このクイックチュートリアルでは、
Javaを使って
InputStream
を
Reader
に変換し、次にGuava、そして最後にApache Commons IOを見ていきます。
この記事はリンクの一部です:/java-tutorial[The
Java – Back to Basic
]シリーズはここBaeldungにあります。
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グアバ
とは
次に、中間のバイト配列とStringを使用して、
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コモンズIO
付き
最後に – Apache Commons IOを使った解決策 – 中間のStringも使って
@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つの簡単な方法があります。