Java - InputStream to Reader
Dans ce rapide tutoriel, nous allons jeter un œil àconverting an InputStream to a Reader utilisant Java, puis Guava et enfin Apache Commons IO.
Cet article fait partie dethe “Java – Back to Basic” series ici par exemple.
1. Avec Java
Tout d'abord, examinons la solution Java simple - en utilisant lesInputStreamReader facilement disponibles:
@Test
public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect()
throws IOException {
InputStream initialStream = new ByteArrayInputStream("With Java".getBytes());
Reader targetReader = new InputStreamReader(initialStream);
targetReader.close();
}
2. Avec goyave
Ensuite - jetons un œil àthe Guava solution - en utilisant un tableau d'octets intermédiaire et une chaîne:
@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();
}
Notez que la solution Java est plus simple que cette approche.
3. Avec Commons IO
Enfin - la solution utilisant Apache Commons IO - utilisant également une chaîne intermédiaire:
@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();
}
Et là vous l'avez - 3 façons rapides de convertir le flux d'entrée en JavaReader.