001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.io;
018
019import com.google.common.annotations.Beta;
020
021import java.io.FilterOutputStream;
022import java.io.IOException;
023import java.io.OutputStream;
024
025import javax.annotation.Nullable;
026
027/**
028 * An OutputStream that counts the number of bytes written.
029 *
030 * @author Chris Nokleberg
031 * @since 1.0
032 */
033@Beta
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(@Nullable OutputStream out) {
044    super(out);
045  }
046
047  /** Returns the number of bytes written. */
048  public long getCount() {
049    return count;
050  }
051
052  @Override public void write(byte[] b, int off, int len) throws IOException {
053    out.write(b, off, len);
054    count += len;
055  }
056
057  @Override public void write(int b) throws IOException {
058    out.write(b);
059    count++;
060  }
061}