001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.io;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.GwtIncompatible;
020import com.google.common.annotations.J2ktIncompatible;
021import java.io.FilterOutputStream;
022import java.io.IOException;
023import java.io.OutputStream;
024
025/**
026 * An OutputStream that counts the number of bytes written.
027 *
028 * @author Chris Nokleberg
029 * @since 1.0
030 */
031@J2ktIncompatible
032@GwtIncompatible
033@ElementTypesAreNonnullByDefault
034public final class CountingOutputStream extends FilterOutputStream {
035
036  private long count;
037
038  /**
039   * Wraps another output stream, counting the number of bytes written.
040   *
041   * @param out the output stream to be wrapped
042   */
043  public CountingOutputStream(OutputStream out) {
044    super(checkNotNull(out));
045  }
046
047  /** Returns the number of bytes written. */
048  public long getCount() {
049    return count;
050  }
051
052  @Override
053  public void write(byte[] b, int off, int len) throws IOException {
054    out.write(b, off, len);
055    count += len;
056  }
057
058  @Override
059  public void write(int b) throws IOException {
060    out.write(b);
061    count++;
062  }
063
064  // Overriding close() because FilterOutputStream's close() method pre-JDK8 has bad behavior:
065  // it silently ignores any exception thrown by flush(). Instead, just close the delegate stream.
066  // It should flush itself if necessary.
067  @Override
068  public void close() throws IOException {
069    out.close();
070  }
071}