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
025/**
026 * An OutputStream that counts the number of bytes written.
027 *
028 * @author Chris Nokleberg
029 * @since 1.0
030 */
031@Beta
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(out);
043  }
044
045  /** Returns the number of bytes written. */
046  public long getCount() {
047    return count;
048  }
049
050  @Override public void write(byte[] b, int off, int len) throws IOException {
051    out.write(b, off, len);
052    count += len;
053  }
054
055  @Override public void write(int b) throws IOException {
056    out.write(b);
057    count++;
058  }
059}