1/*
2 * Copyright (C) 2007 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.io;
18
19import com.google.common.annotations.Beta;
20
21import java.io.FilterOutputStream;
22import java.io.IOException;
23import java.io.OutputStream;
24
25/**
26 * An OutputStream that counts the number of bytes written.
27 *
28 * @author Chris Nokleberg
29 * @since 1.0
30 */
31@Beta
32public final class CountingOutputStream extends FilterOutputStream {
33
34  private long count;
35
36  /**
37   * Wraps another output stream, counting the number of bytes written.
38   *
39   * @param out the output stream to be wrapped
40   */
41  public CountingOutputStream(OutputStream out) {
42    super(out);
43  }
44
45  /** Returns the number of bytes written. */
46  public long getCount() {
47    return count;
48  }
49
50  @Override public void write(byte[] b, int off, int len) throws IOException {
51    out.write(b, off, len);
52    count += len;
53  }
54
55  @Override public void write(int b) throws IOException {
56    out.write(b);
57    count++;
58  }
59}
60