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 java.io.FilterOutputStream;
021import java.io.IOException;
022import java.io.OutputStream;
023
024/**
025 * An OutputStream that counts the number of bytes written.
026 *
027 * @author Chris Nokleberg
028 * @since 1.0
029 */
030@GwtIncompatible
031@ElementTypesAreNonnullByDefault
032public final class CountingOutputStream extends FilterOutputStream {
033
034  private long count;
035
036  /**
037   * Wraps another output stream, counting the number of bytes written.
038   *
039   * @param out the output stream to be wrapped
040   */
041  public CountingOutputStream(OutputStream out) {
042    super(checkNotNull(out));
043  }
044
045  /** Returns the number of bytes written. */
046  public long getCount() {
047    return count;
048  }
049
050  @Override
051  public void write(byte[] b, int off, int len) throws IOException {
052    out.write(b, off, len);
053    count += len;
054  }
055
056  @Override
057  public void write(int b) throws IOException {
058    out.write(b);
059    count++;
060  }
061
062  // Overriding close() because FilterOutputStream's close() method pre-JDK8 has bad behavior:
063  // it silently ignores any exception thrown by flush(). Instead, just close the delegate stream.
064  // It should flush itself if necessary.
065  @Override
066  public void close() throws IOException {
067    out.close();
068  }
069}