Utilisation de Guava CountingOutputStream

Utilisation de Guava CountingOutputStream

 

1. Vue d'ensemble

Dans ce didacticiel, nous allons examiner la classeCountingOutputStream et comment l'utiliser.

La classe peut être trouvée dans des bibliothèques populaires commeApache Commons ouGoogle Guava. Nous allons nous concentrer sur la mise en œuvre dans la bibliothèque Guava.

2. CountingOutputStream

2.1. Dépendance Maven

CountingOutputStream fait partie du package Guava de Google.

Commençons par ajouter la dépendance auxpom.xml:


    com.google.guava
    guava
    24.1-jre

La dernière version de la dépendance peut être vérifiéehere.

2.2. Détails des cours

La classe étendjava.io.FilterOutputStream, remplace les méthodeswrite() etclose() et fournit la nouvelle méthodegetCount().

Le constructeur prend un autre objetOutputStream comme paramètre d'entrée. While writing data, the class then counts the number of bytes written into this OutputStream.

Afin d'obtenir le décompte, nous pouvons simplement appelergetCount() pour renvoyer le nombre actuel d'octets:

/** Returns the number of bytes written. */
public long getCount() {
    return count;
}

3. Cas d'utilisation

UtilisonsCountingOutputStream dans un cas d’utilisation pratique. À titre d'exemple, nous allons mettre le code dans un test JUnit pour le rendre exécutable.

Dans notre cas, nous allons écrire des données dans unOutputStream et vérifier si nous avons atteint une limite deMAX octets.

Une fois la limite atteinte, nous voulons interrompre l'exécution en lançant une exception:

public class GuavaCountingOutputStreamUnitTest {
    static int MAX = 5;

    @Test(expected = RuntimeException.class)
    public void givenData_whenCountReachesLimit_thenThrowException()
      throws Exception {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        CountingOutputStream cos = new CountingOutputStream(out);

        byte[] data = new byte[1024];
        ByteArrayInputStream in = new ByteArrayInputStream(data);

        int b;
        while ((b = in.read()) != -1) {
            cos.write(b);
            if (cos.getCount() >= MAX) {
                throw new RuntimeException("Write limit reached");
            }
        }
    }
}

4. Conclusion

Dans cet article rapide, nous avons examiné la classeCountingOutputStream et son utilisation. La classe fournit la méthode supplémentairegetCount() qui renvoie le nombre d'octets écrits jusqu'ici dans lesOutputStream.

Enfin, comme toujours, le code utilisé lors de la discussion se trouveover on GitHub.