CountingOutputStream.java

  1. /*
  2.  * Copyright (C) 2011, Google Inc. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.util.io;

  11. import java.io.IOException;
  12. import java.io.OutputStream;

  13. /**
  14.  * Counts the number of bytes written.
  15.  */
  16. public class CountingOutputStream extends OutputStream {
  17.     private final OutputStream out;
  18.     private long cnt;

  19.     /**
  20.      * Initialize a new counting stream.
  21.      *
  22.      * @param out
  23.      *            stream to output all writes to.
  24.      */
  25.     public CountingOutputStream(OutputStream out) {
  26.         this.out = out;
  27.     }

  28.     /**
  29.      * Get current number of bytes written.
  30.      *
  31.      * @return current number of bytes written.
  32.      */
  33.     public long getCount() {
  34.         return cnt;
  35.     }

  36.     /** {@inheritDoc} */
  37.     @Override
  38.     public void write(int val) throws IOException {
  39.         out.write(val);
  40.         cnt++;
  41.     }

  42.     /** {@inheritDoc} */
  43.     @Override
  44.     public void write(byte[] buf, int off, int len) throws IOException {
  45.         out.write(buf, off, len);
  46.         cnt += len;
  47.     }

  48.     /** {@inheritDoc} */
  49.     @Override
  50.     public void flush() throws IOException {
  51.         out.flush();
  52.     }

  53.     /** {@inheritDoc} */
  54.     @Override
  55.     public void close() throws IOException {
  56.         out.close();
  57.     }
  58. }