Java - Lecteur en chaîne

Java - Lecteur en chaîne

Dans ce tutoriel rapide, nous allons utiliserconvert a Reader into a String en utilisant Java, Guava et la bibliothèque Apache Commons IO.

Cet article fait partie dethe “Java – Back to Basic” series ici par exemple.

1. Avec Java

Commençons par une solution Java simple quireads characters sequentially from the Reader:

@Test
public void givenUsingPlainJava_whenConvertingReaderIntoStringV1_thenCorrect()
  throws IOException {
    StringReader reader = new StringReader("text");
    int intValueOfChar;
    String targetString = "";
    while ((intValueOfChar = reader.read()) != -1) {
        targetString += (char) intValueOfChar;
    }
    reader.close();
}

S'il y a beaucoup de contenu à lire, une solution de lecture en bloc fonctionnera mieux:

@Test
public void givenUsingPlainJava_whenConvertingReaderIntoStringV2_thenCorrect()
  throws IOException {
    Reader initialReader = new StringReader("text");
    char[] arr = new char[8 * 1024];
    StringBuilder buffer = new StringBuilder();
    int numCharsRead;
    while ((numCharsRead = initialReader.read(arr, 0, arr.length)) != -1) {
        buffer.append(arr, 0, numCharsRead);
    }
    initialReader.close();
    String targetString = buffer.toString();
}

2. Avec goyave

Guava fournit un utilitaire qui peutdo the conversion directly:

@Test
public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect()
  throws IOException {
    Reader initialReader = CharSource.wrap("With Google Guava").openStream();
    String targetString = CharStreams.toString(initialReader);
    initialReader.close();
}

3. Avec Commons IO

Idem avec Apache Commons IO - il existe un utilitaire IO capable d'exécuter lesdirect conversion:

@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoString_thenCorrect()
  throws IOException {
    Reader initialReader = new StringReader("With Apache Commons");
    String targetString = IOUtils.toString(initialReader);
    initialReader.close();
}

Et là vous l'avez - 4 façons de transformer unReader en une chaîne simple.