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